I had the following code:
[Required(ErrorMessage = MessageModel.translateMessage("required")))]
[Display(Name= MessageModel.translateMessage("id"))]
public string user_id { get; set; }
I am trying to make the error message dynamic but I get error when compiled.:
"An attribute argument must be a constant expression , typeof expression or array creation expression of an attribute parameter type."
Any solution for this issue?
First you create a Resource .resx file this will contain your localised strings.
When you declare the attribute you set the ResourceType argument. This causes the Name, ShortName and Description arguments to be used as a resource key instead of a value.
[Display(Name = "GenreName", ShortName = "GenreShortName", Description = "GenreDescription", ResourceType = typeof(MyResources))]
public string Genre { get; set; }
The error message says "an attribute argument must be a constant expression...".
It means that the argument to the DisplayName
attribute must be a constant expression (such as a string, integer, etc.), or any of the other expression types listed in the error message.
If you want to localize a property then you need an attribute that supports it.If you are using ASP.Net 4 then DisplayAttribute should be like this:
[Display(Name="ID",Resource=typeof(MessageModel.translateMessage("id")))]
public string user_id { get; set; }
Also please check this answer from Darin
Responding very late.
DataAnnotations param values require constants, actual strings. So, you cann't write a method here. Is you need any type of localization then create resource file. Then write code something like this. Here "RequiredField" and "Email" are key created in resource file and "ViewModelResource" is name of resource file.
[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(ViewModelResource))]
[Display(Name = "Email", ResourceType=typeof(ViewModelResource))]
public string Email{ get; set; }
If you want custom message on conditions then create your own "Custom DataAnnotations" depends upon conditions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With