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

标签 .net asp.net-mvc-2 data-annotations asp.net-mvc-2-validation

有一种方法可以将默认资源设置为数据注释验证?

我不想做这样的事情:

[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开始有效,因为在MVC2中引入了DataAnnotationsModelValidatorProvider。

关于.net - ASP.NET MVC中数据注释的默认资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260748/

相关文章:

.net - AppDomain.UnhandledException 事件如何工作?

.net - 取消 e.result 中的后台工作异常

c# - System.IO.Stream.Read 卡住

c# - 在 linux 服务上处理 kill - .NET Core 1.1

c# - MVC 到 MVC2 错误

asp.net-mvc - NHibernate.Validator 与 DataAnnotations

asp.net - MVC - 单击单选按钮后的回发

c# - 从 ASP.NET MVC 2 站点下载文件

c# - .NET Core - 在模型中获取 DbContext

asp.net - Entity Framework : how to implement shared primary key with Fluent API?