mvc : I want to load my error message from resource file but i get attribute const error [closed]

↘锁芯ラ 提交于 2020-01-15 12:22:31

问题


I want to create a multilingual mvc web site so I have been loading all my messages and labels from resource file and in my validation i want show my message from the resource file but i am getting the following error.

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

回答1:


Attribute parameters are restricted to constant values.

That is, when applying an attribute to something, the arguments must be constant values such as const primitives (string, int, float, bool, double etc), enums, or type.

For example:

Legal

[Required("This field is required.")]
public string Username { get; set; }

Error

[Required(SomeObject.ErrorMessageStringProperty)]
public string Username { get; set; }

If the string isn't a const, you cannot compile.

Hint

ValidationAttribute classes have already addressed this issue. Instead of providing an ErrorMessage argument, you can provide an ErrorMessageResourceType and ErrorMessageResourceName. These const values are then used to look up the appropriate error message for the culture.

e.g.

Legal

[Required(ErrorMessageResourceType = typeof(Resources.Errors), ErrorMessageResourceName="RequiredError")]
public string Username { get; set; }

Further reading

How to localize ASP.NET MVC application?

Multiple languages in an ASP.NET MVC application?

DisplayName attribute from Resources?

Best Practice for Asp.net MVC Resource Files



来源:https://stackoverflow.com/questions/24177177/mvc-i-want-to-load-my-error-message-from-resource-file-but-i-get-attribute-con

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