2013-02-21 45 views
8

我有以下代碼的表達或數組創建表達式:ASP.NET MVC4:屬性參數必須是常量表達式的typeof屬性參數類型

[Required(ErrorMessage = MessageModel.translateMessage("required")))] 
    [Display(Name= MessageModel.translateMessage("id"))] 
    public string user_id { get; set; } 

我試圖使該錯誤消息動態但是,當編譯:

"An attribute argument must be a constant expression , typeof expression or array creation expression of an attribute parameter type."

針對此問題的任何解決方案,我得到的錯誤?

+0

看看這個問題:http://stackoverflow.com/questions/3814866/dynamic-parameters-for-attributes – 2013-02-21 09:51:52

+1

這導致發貼由Eric Lippert:http://blogs.msdn.com/b/ericlippert/ archive/2009/02/02/properties-vs-attributes.aspx – 2013-02-21 09:53:31

+0

[C#Dynamic Attribute Arguments](http://stackoverflow.com/questions/1093466/c-sharp-dynamic-attribute-arguments) – jgauffin 2013-02-21 10:00:24

回答

3

錯誤消息顯示「屬性參數必須是常量表達式...」。

這意味着DisplayName屬性的參數必須是一個常量表達式(例如字符串,整數等)或錯誤消息中列出的任何其他表達式類型。

如果你要本地化的屬性,那麼你需要的是支持您所使用ASP.Net 4吧。如果一個屬性然後DisplayAttribute應該是這樣的:

[Display(Name="ID",Resource=typeof(MessageModel.translateMessage("id")))] 
public string user_id { get; set; } 

也請從達林

檢查這個 answer
+1

translateMessage (「id」)不是一種類型,所以我認爲它不起作用 – MiaoWin 2013-02-21 10:09:05

9

首先,您將創建一個資源.resx文件,其中將包含您的本地化字符串。

當您聲明該屬性時,您設置了ResourceType參數。這會導致Name,ShortName和Description參數被用作資源鍵而不是值。

[Display(Name = "GenreName", ShortName = "GenreShortName", Description = "GenreDescription", ResourceType = typeof(MyResources))] 
public string Genre { get; set; } 
2

響應很晚。

DataAnnotations參數值需要常量,實際字符串。 所以,你不能在這裏寫一個方法。你需要任何類型的本地化,然後創建資源文件。然後編寫這樣的代碼。這裏「RequiredField」和「Email」是在資源文件中創建的關鍵字,「ViewModelResource」是資源文件的名稱。

[Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(ViewModelResource))] 
[Display(Name = "Email", ResourceType=typeof(ViewModelResource))] 
public string Email{ get; set; } 

如果你想在條件自定義消息,然後創建自己的「自定義DataAnnotations」取決於條件。

相關問題