有一种方法可以将默认资源设置为数据注释验证?
我不想这样做:
[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); } } }
// 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中引入的。