1

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 Answer 1

2

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

##ASP.NET 5/Core

For devs coming across this post in the future and are seeking the .NET 5 reference... the following documentation cleared everything up for me.

Globalization and localization in ASP.NET Core

Sign up to request clarification or add additional context in comments.

4 Comments

but my resource file created a static string eg public static string ClaimamountlessthanBalanceamount { get { return ResourceManager.GetString("ClaimamountlessthanBalanceamount", resourceCulture); } }
That's a static property, not a const. Property values are not a legal argument in an attribute.
what's the best way to do it
I've added a section to hint you in the right direction. Use that information and the further reading for ideas.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.