在ASP.NET MVC数据注解默认的资源 [英] Default resource for data annotations in ASP.NET MVC
问题描述
有对默认的资源设置为数据注释验证的方法?
There's a way to set the default resource to the data annotations validations?
我不想做这样的事情:
[Required(ErrorMessage="Name required.", ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }
我想是这样的:
的Global.asax
DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources);
然后
[Required]
public string Name { get; set; }
有人给我一个光芒!
someone gimme a light!
在此先感谢
修改
我真正的问题是与EF code首先CTP4。 CTP5修复它。谢谢大家。
My real problem was with EF Code First CTP4. CTP5 fix it. Thanks for everyone.
推荐答案
您可以尝试这样做:
在项目中的某处加入这个类:
Add this class somewhere in your project:
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中,添加以下内容:
and in your global.asax, add the following:
// Add once
ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources);
// Add one line for every attribute you want their ErrorMessageResourceType replaced.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(ExternalResourceDataAnnotationsValidator));
这将查找具有相同名称的验证类型错误消息的一个属性。您可以通过ResourceNameFunc属性更改。
It will look for a property with the same name as the validator type for the error message. You can change that via the ResourceNameFunc property.
编辑:据我所知这从MVC2工作起,因为DataAnnotationsModelValidatorProvider在MVC2介绍
AFAIK this works from MVC2 onwards, as DataAnnotationsModelValidatorProvider was introduced in MVC2.
这篇关于在ASP.NET MVC数据注解默认的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!