我将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,观看2010年1月9日下午6:20的bradwils消息。
该解决方案对我来说效果很好。
知道可覆盖消息的完整列表应该很有趣。
更新
这里的帖子内容:
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-mvc - 为ASP.Net MVC 2中的非归因模型验证提供本地化的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2480557/