在我的ASP.NET MVC应用程序中,我有一个表单,并且我使用了一个ViewModel,因此ModelBinder可以绑定到我的强类型类。我正在使用DataAnnotations进行验证
public class FormViewModel
{
[Required]
public string SomeValue {get;set;}
[Range(0, 10, ErrorMessage="Enter a number between 0 and 10.")]
public byte? SomeOtherValue {get;set;}
}这很好用。然而,问题是当用户没有为SomeOtherValue输入有效的值(如abc)时,会弹出一个标准的MVC错误:‘值'abc’对'SomeOtherValue‘无效。这真的很烦人,因为我不能定制这条消息。我知道有一些方法可以本地化这个消息,但那是没有意义的(我不想要一般的消息,我想要一个特定于值的值)。
我尝试将RegularExpression-attribute应用于“SomeOtherValue”,它只允许字节值,但标准验证可能会“覆盖”此验证。有没有办法为属性应用自定义的“值无效”消息,或者禁用标准消息?
发布于 2013-10-11 04:33:48
如果自定义验证属性对您不起作用,这里有一个不同的(非理想方式,IMHO)来修复它。在控制器中:
if (!ModelState.IsValid)
{
string fieldName = "ThatFieldName";
var m = ViewData.ModelState[fieldName];
if (m != null && m.Errors.Count > 0)
{
ViewData.ModelState.Remove(fieldName);
ViewData.ModelState.AddModelError(fieldName, "You mucked that field up.");
}
}https://stackoverflow.com/questions/9610822
复制相似问题