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

标签 asp.net-mvc localization data-annotations

我将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/

相关文章:

android - 如何避免因缺少字符串条目而导致崩溃?

ios 应用程序在语言更改后崩溃

swift - 如何在 Swift 中获取本地化的文件大小单位

entity-framework-4 - EF4 CodeFirst CTP5 nvarchar(max) 通过属性

c# - 如何覆盖默认的必需错误消息

c# - 使用 open graph for asp .net mvc 正确共享

c# - 如何检测不同的用户设置?启用 Javascript,启用 Cookie

asp.net - Azure Active Directory 分配的用户被忽略

asp.net - 如何为 ASP Razor MVC 设置默认布局

.net - DataAnnotations 与 IDataErrorInfo