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

空扰寡人 提交于 2019-12-22 04:37:11

问题


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?


回答1:


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; }



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/14999117/asp-net-mvc4-an-attribute-argument-must-be-a-constant-expression-typeof-expre

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