How localize ErrorMessage in DataAnnotation?

孤者浪人 提交于 2019-12-01 15:57:38

问题


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?


回答1:


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




回答2:


You don't need anything, just create your resource file in right place.

For example Resources > ViewModels > LoginVm.en-US.resx

in LoginVm: [Required(ErrorMessage = "სახელი არის აუცილებელი")] < (it's Georgian Language)

and in LoginVm.en-US.resx just add

სახელი არის აუცილებელი > UserName is Required

and all done.



来源:https://stackoverflow.com/questions/20699594/how-localize-errormessage-in-dataannotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!