1

我需要在MVC 2.0中设置DataAnnotation的验证属性的ErrorMessage属性。例如,我应该能够传递一个ID,而不是为Model属性实际的错误信息,例如...ASP.NET MVC 2.0验证和ErrorMessages

[StringLength(2, ErrorMessage = "EmailContentID")] 
[DataType(DataType.EmailAddress)]   
public string Email { get; set; } 

然后用这个ID(“EmailContentID”)来检索某些内容(错误消息)来自另一个服务例如数据库。然后错误错误消息显示给用户而不是ID。为了做到这一点,我需要设置DataAnnotation验证属性的ErrorMessage属性。

它通过只重写DataAnnotationsModelValidatorProvider的保护覆盖的IEnumerable GetValidators(ModelMetadata元,ControllerContext背景下,IEnumerable的属性)

但是它现在复杂的似乎是一个挺直向前任务....

一MVC DatannotationsModelValidator的ErrorMessage属性是只读的。所以我不能在这里设置任何东西。B.已经在MVC DatannotationsModelValidator中设置了System.ComponentModel.DataAnnotationErrorMessage属性(get和set),所以我不能再设置它。如果我尝试设置它,我会得到“该属性不能设置多次...”错误消息。

public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider 
{ 
     protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) 
     { 
      IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes); 

      foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>()) 
      { 
       messageId = validator.ErrorMessage; 
       validator.ErrorMessage = "Error string from DB And" + messageId ; 
      } 

      //...... 
     } 
    } 

任何人都可以请给我正确的方向吗?

在此先感谢。

回答

0

我个人wouldnt创建一个新的提供程序继承原始提供程序,但我会创建一个新的属性继承ValidationAttribute或StringLengthAttribute。

像这样

public class MyNewValidationAttribute : StringLengthAttribute 
{ 
    public int ErrorMessageId 
    { 
     set { 
       var myErrorMessageFromDB = ""; //query database and get message. 
       this.ErrorMessage = myErrorMessageFromDB; 
      } 
    } 
} 

现在,当您指定的属性

[StringLength(2, ErrorMessageId = 1 //equals id from database 
)] 
+1

(迁移评论)“非常感谢,但如果我从System.ComponentModel.DataAnnotations.ValidationAttribute 继承哪有我确信MVC2 DataAnnotation中使用的这些属性可以同时处理客户端和服务器验证。我怎样才能注册这个新属性,以便MVC2标准验证属性总是可以挂钩到新的属性中? - Raj Aththanayake – Sampson 2010-04-15 02:35:40