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

全局本地化验证

发布时间:2020-12-16 07:22:30 所属栏目:asp.Net 来源:网络整理
导读:我正在使用System.ComponeneModel.DataAnnotations属性,例如Required和StringLength.是否可以全局本地化其错误消息? 我知道我能做到这一点 [Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources.Validation))] 但
我正在使用System.ComponeneModel.DataAnnotations属性,例如Required和StringLength.是否可以全局本地化其错误消息?

我知道我能做到这一点

[Required(ErrorMessageResourceName = "Required",ErrorMessageResourceType = typeof(Resources.Validation))]

但到处都这样,我使用必需的属性将是疯狂的.另外我想避免像这样的东西:

public class LocalizedRequiredAttribute : RequiredAttribute {
    public LocalizedRequiredAttribute()
        : base() {
        ErrorMessageResourceName = "Required";
        ErrorMessageResourceType = typeof(Resources.Validation);
    }
}

(但如果没有其他办法,我会满足于此)

解决方法

AFAIK您需要自定义属性或指定ErrorMessageResourceName和ErrorMessageResourceType属性.还有另一种可能性 detailed here:

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.

(编辑:李大同)

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

    推荐文章
      热点阅读