asp.net-mvc – 在ASP.Net MVC 2中为非归因模型验证提供本地化错误消息?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在ASP.Net MVC 2中为非归因模型验证提供本地化错误消息?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 DataAnnotations属性以及ASP.Net MVC 2为我的viewmodels提供模型验证:
public class ExamplePersonviewmodel {
    [required(ErrorMessageResourceName = "required",ErrorMessageResourceType = typeof(Resources.Validation))]
    [StringLength(128,ErrorMessageResourceName = "StringLength",ErrorMessageResourceType = typeof(Resources.Validation))]
    [DataType(DataType.Text)]
    public string Name { get; set; }

    [required(ErrorMessageResourceName = "required",ErrorMessageResourceType = typeof(Resources.Validation))]
    [DataType(DataType.Text)]
    public int Age { get; set; }
}

这似乎像预期的那样工作(尽管它很详细)。我遇到的问题是,执行的幕后模型验证与任何特定属性无关。上述模型中的一个例子是,Age属性需要是一个int。如果您尝试在表单上输入一个非整数值,则会出现以下(非本地化)消息的错误

The field Age must be a number.

这些非属性验证消息如何被本地化?

是否有完整的这些消息列表可用,所以我可以确保它们都是本地化的?

解决方法

转到 http://forums.asp.net/p/1512140/3608427.aspx,观看bradwils消息日期:01-09-2010,6:20 PM。

这个解决方案对我来说很好。

知道可覆盖的消息的完整列表应该是有趣的…

UPDATE

这里的帖子内容

Create a global resource class in App_GlobalResources,and set DefaultModelBinder.ResourceClassKey to the name of this class (for example,if you made “Messages.resx”,then set ResourceClassKey to “Messages”).

There are two strings you can override in MVC 2:

  • The string value for “PropertyValueInvalid” is used when the data the user entered isn’t compatible with the data type (for example,typing in “abc” for an integer field). The default message for this is: “The value ‘{0}’ is not valid for {1}.”
  • The string value for “PropertyValuerequired” is used when the user did not enter any data for a field which is not nullable (for example,an integer field). The default message for this is: “A value is required.”

It’s important to note in the second case that,if you have the DataAnnotationsModelValidatorProvider in your validator providers list (which it is by default),then you will never see this second message. This provider sees non-optional fields and adds an implied [required] attribute to them so that their messages will be consistent with other fields with explicit [required] attributes and to ensure that you get client-side validation for required fields.

猜你在找的asp.Net相关文章