简体   繁体   中英

ASP.NET MVC 2.0 Validation and ErrorMessages

I need to set the ErrorMessage property of the DataAnnotation's validation attribute in MVC 2.0. For example I should be able to pass an ID instead of the actual error message for the Model property, for example...

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

Then use this ID ("EmailContentID") to retrieve some content(error message) from a another service eg database. Then the error error message is displayed to the user instead of the ID. In order to do this I need to set the DataAnnotation validation attribute's ErrorMessage property.

It seems like a stright forward task by just overriding the DataAnnotationsModelValidatorProvider's protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)

However it is complicated now....

A. MVC DatannotationsModelValidator's ErrorMessage property is readonly. So I cannot set anything here B. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so I cannot set it again. If I try to set it I get “The property cannot set more than once…” error message.

 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 ; 
             } 

            //...... 
       } 
  } 

Can anyone please give me the right direction on this?

Thanks in advance.

I personally wouldnt create a new provider inheriting the original provider but I would create a new Attribute inheriting either the ValidationAttribute or the StringLengthAttribute.

Something Like this

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

Now when you assign the attribute

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM