My task is to change the ErrorMessage property of the DataAnnotation validation attribute in MVC2.0. For example, I should be able to pass the identifier instead of the actual error message for the Model property and use this identifier to get some content (error message) from another service, such as a database, and display this error message in the view instead of I would. To do this, I need to set the attributes of the DataAnnotation ErrorMessage attribute.
[StringLength(2, ErrorMessage = "EmailContentID.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
It seems like an easy task by simply overriding DataAnnotationsModelValidatorProvider's secure override of IEnumerable GetValidators (ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
However, this seems rather complicated.
and. MVC DatannotationsModelValidators The ErrorMessage property is read-only. Therefore, I can’t install anything here b. The System.ComponentModel.DataAnnotationErrorMessage (get and set) property, which is already set in MVC DatannotationsModelValidator, so we cannot set it again. If you try to install, you will receive the error message "Unable to install more than once ...".
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 help me with this?
source
share