GibboK GibboK - 11 months ago 50
C# Question

How localize ErrorMessage in DataAnnotation?

Using MVC 5 I need to localize an ErrorMessage for a DataAnnotation attributes.
I receive the following error


An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

In model

[Compare("Password", ErrorMessage = Resources.Account_Register_ConfirmPasswordErrorMessage)]
public string ConfirmPassword { get; set; }

Any idea how to fix it?


You need to use ErrorMessageResourceName and ErrorMessageResourceType properties.

For example like this:

[Compare("Password", ErrorMessageResourceName = "ConfirmPasswordErrorMessage", ErrorMessageResourceType=typeof(<<type_of_your_resoruce_class>>)]
public string ConfirmPassword { get; set; }

Here is also a link to MSDN, where you can find explanation for both properties.

Hope this helps!

Regards, Uros