2010-05-28 87 views
1

我有一个必需的属性与资源使用:ASP.NET MVC 2:数据DataAnnotations验证是惯例

public class ArticleInput : InputBase 
{ 
    [Required(ErrorMessageResourceType = typeof(ArticleResources), ErrorMessageResourceName = "Body_Validation_Required")] 
    public string Body { get; set; } 
} 

我想指定资源成为惯例,这样的:

public class ArticleInput : InputBase 
{ 
    [Required2] 
    public string Body { get; set; } 
} 

基本上,Required2实施基于此数据的值:

ErrorMessageResourceType = typeof(ClassNameWithoutInput + Resources); // ArticleResources 
ErrorMessageResourceName = typeof(PropertyName + "_Validation_Required"); // Body_Validation_Required 

Is there任何方式来实现这样的事情?也许我需要实施一个新的ValidationAttribute

回答

1

我不认为这是可能的,或者至少,如果不为该属性提供自定义适配器,也不可能做到这一点。您在属性的构造函数中没有任何方式来访问该属性应用于的方法/属性。没有这些,你无法获得类型或属性名称信息。

如果您为属性创建了适配器,然后使用DataAnnotationsModelValidatorProvider注册它,那么在GetClientValidationRules中,您将有权访问ControllerContext和模型元数据。从中您可能能够派生出正确的资源类型和名称,然后查找正确的错误消息并将其添加到属性的客户端验证规则中。

public class Required2AttributeAdapter 
    : DataAnnotationsModelValidator<Required2Attribute> 
{ 
    public Required2AttributeAdapter(ModelMetadata metadata, 
             ControllerContext context, 
             Required2Attribute attribute) 
     : base(metadata, context, attribute) 
    { 
    } 

    public override IEnumerable<ModelClientValidationRule> 
     GetClientValidationRules() 
    { 
     // use this.ControllerContext and this.Metadata to find 
     // the correct error message from the correct set of resources 
     // 
     return new[] { 
      new ModelClientValidationRequiredRule(localizedErrorMessage) 
     }; 
    } 
} 

然后在的global.asax.cs

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(Required2Attribute), 
    typeof(Required2AttributeAdapter) 
); 
+0

我可以用一个适配器与任何验证属性?只需使用'DataAnnotationsModelValidator '? – stacker 2010-05-28 21:05:13

+0

@stacker - 现有的属性已经注册了适配器。内部字典的确切类型也是如此,所以我认为您需要为每个属性类型配备一个适配器。 – tvanfosson 2010-05-28 21:25:44