2011-07-07 33 views
2

我正在尋找一種更簡單/更乾燥的方法來使用資源我的MVC 3模型。在c#中爲模型上的屬性設置默認資源類型

這是怎麼了,現在我做(需要每個屬性被告知它使用的ressource型):

public class ContactMessageModel:BaseModel 
    { 
     [Display(Name="ReplyToEmail_DisplayName", ResourceType = typeof(Res.Views_Contact))] 
     public string ReplyToEmail {get; set; } 

     [Display(Name = "ContactReason_DisplayName", ResourceType = typeof(Res.Views_Contact))] 
     public string ContactReason { get; set; } 

可以這樣做?

這是我想做到這一點(我只是想一次定義爲模型的資源型):

[Display(ResourceType = typeof(Res.Views_Contact))] 
public class ContactMessageModel:BaseModel 
{ 
    [Display(Name="ReplyToEmail_DisplayName")] 
    public string ReplyToEmail {get; set; } 

    [Display(Name = "ContactReason_DisplayName")]    
    public string ContactReason { get; set; } 
+0

你試過了嗎? –

+0

錯誤是:)。給我一個錯誤:屬性'Display'在這個聲明類型上是無效的。它只對'方法,屬性,索引器,字段,參數'聲明有效。 – AyKarsi

回答

1

似乎並不可能,因爲屬性實例將需要訪問它所在的屬性,.NET不支持。

0

是的,默認ResourceType可以完成。菲爾哈克展示如何重寫.NET的ModelMetadataProviders一個例子來做到這一點,並防止其重複自己一遍又一遍地指定相同的ResourceType:

http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/

您可以默認爲一個單一的ResourceType全球範圍內,或裝飾默認使用他定義的這個屬性的具體類:

public class MetadataConventionsAttribute : Attribute 
{ 
    public Type ResourceType { get; set; } 
} 
相關問題