问题
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