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

ASP.NET MVC中数据注释的默认资源

发布时间:2020-12-16 00:39:38 所属栏目:asp.Net 来源:网络整理
导读:有一种方法可以将默认资源设置为数据注释验证? 我不想这样做: [Required(ErrorMessage="Name required.",ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]public string Name { get; set; } 我想要这样的东西: Global.asax中 DataAnnot
有一种方法可以将默认资源设置为数据注释验证?

我不想这样做:

[Required(ErrorMessage="Name required.",ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }

我想要这样的东西:

Global.asax中

DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources);

然后

[Required]
public string Name { get; set; }

有人给我一个光!

提前致谢

编辑

我的真正问题是EF Code First CTP4。 CTP5修复它。感谢大家

解决方法

你可以尝试这样做:

将此类添加到项目中的某个地方:

public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
    /// <summary>
    /// The type of the resource which holds the error messqages
    /// </summary>
    public static Type ResourceType { get; set; }

    /// <summary>
    /// Function to get the ErrorMessageResourceName from the Attribute
    /// </summary>
    public static Func<ValidationAttribute,string> ResourceNameFunc 
    {
        get { return _resourceNameFunc; }
        set { _resourceNameFunc = value; }
    }
    private static Func<ValidationAttribute,string> _resourceNameFunc = attr => attr.GetType().Name;

    public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata,ControllerContext context,ValidationAttribute attribute)
        : base(metadata,context,attribute)
    {
        if (Attribute.ErrorMessageResourceType == null)
        {
            this.Attribute.ErrorMessageResourceType = ResourceType;
        }

        if (Attribute.ErrorMessageResourceName == null)
        {
            this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
        }
    }
}

并在global.asax中添加以下内容:

// Add once
ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources);

// Add one line for every attribute you want their ErrorMessageResourceType replaced.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute),typeof(ExternalResourceDataAnnotationsValidator));

它将查找与错误消息的验证器类型相同名称的属性。您可以通过ResourceNameFunc属性更改它。

编辑:AFAIK这是从MVC2起的作品,因为DataAnnotationsModelValidatorProvider是在MVC2中引入的。

(编辑:李大同)

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

    推荐文章
      热点阅读