Dot-Net
ASP.NET MVC 中數據註釋的預設資源
有一種方法可以將預設資源設置為數據註釋驗證?
我不想做這樣的事情:
[Required(ErrorMessage="Name required.", ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)] public string Name { get; set; }我想要這樣的東西:
全球.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 中引入的。