GibboK GibboK - 3 months ago 10
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

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?

Answer

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.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute(v=vs.110).aspx

Hope this helps!

Regards, Uros