Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnnotations not using DisplayName Attribute in Error Messages

In my application, I'm using the dataAnotation as below for validating my ViewModels:

[DisplayName("Provider Business Name") ]
[StringLength(35)]
public string ProviderBusinessName
{
    get { return _providerBusinessName; }
    set { _providerBusinessName = value.ToUpper(); }
}

My environment is Asp.Net Webforms 4.0 and I'm manually invoking the validation with the following code:

dynamic context = new ValidationContext(datamodel, serviceProvider: null, items: null);
results = new List<ValidationResult>();
return Validator.TryValidateObject(datamodel, context, 
                                   results, validateAllProperties: true);

My problem is that the error messages are using the property name instead of the contents of the DisplayName attribute. As far as I can see, the validation attributes should use the DisplayName in the error message.

like image 715
photo_tom Avatar asked Sep 07 '25 01:09

photo_tom


1 Answers

Try using Display property instead (that will make it work for your validation give you the power to use Resources there to be localized):

 [Display(Name = "Provider Business Name")]
like image 170
Aram Avatar answered Sep 09 '25 14:09

Aram