Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC4: An attribute argument must be a constant expression , typeof expression or array creation expression of an attribute parameter type

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?

like image 266
MiaoWin Avatar asked Feb 21 '13 09:02

MiaoWin


3 Answers

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; }
like image 118
ywm Avatar answered Nov 20 '22 07:11

ywm


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

like image 34
Karthik Chintala Avatar answered Nov 20 '22 06:11

Karthik Chintala


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.

like image 2
Kishan Choudhary Avatar answered Nov 20 '22 08:11

Kishan Choudhary