加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:45:38 所属栏目:asp.Net 来源:网络整理
导读:我正在使用 DataAnnotations属性以及ASP.Net MVC 2为我的ViewModels提供模型验证: public class ExamplePersonViewModel { [Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources.Validation))] [StringLength(128
我正在使用 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读