14

我使用自定義資源提供程序從數據庫獲取資源字符串。這適用於ASP.NET,我可以將資源類型定義爲字符串。 MVC 3中模型屬性的元數據屬性(如[Range],[Display],[Required])要求Resource的類型作爲參數,其中ResourceType是.resx文件生成的代碼隱藏類的類型。ASP.NET MVC 3本地化DisplayAttribute和自定義資源提供程序

[Display(Name = "Phone", ResourceType = typeof(MyResources))] 
    public string Phone { get; set; } 

因爲我沒有.resx文件,這樣一類不存在。我如何使用該模型用自定義資源提供者的屬性?

我想有這樣的事情:

[Display(Name = "Telefon", ResourceTypeName = "MyResources")] 
    public string Phone { get; set; } 

System.ComponentModel中的DisplayNameAttribute有一個可覆蓋的DisplayName屬性用於此目的,但DisplayAttribute類是密封的。對於驗證屬性,不存在相應的類。

回答

4

可以擴展DisplayNameAttribute並重寫顯示名稱字符串屬性。我有這樣的事情

public class LocalizedDisplayName : DisplayNameAttribute 
    { 
     private string DisplayNameKey { get; set; } 
     private string ResourceSetName { get; set; } 

     public LocalizedDisplayName(string displayNameKey) 
      : base(displayNameKey) 
     { 
      this.DisplayNameKey = displayNameKey; 
     } 


     public LocalizedDisplayName(string displayNameKey, string resourceSetName) 
      : base(displayNameKey) 
     { 
      this.DisplayNameKey = displayNameKey; 
      this.ResourceSetName = resourceSetName; 
     } 

     public override string DisplayName 
     { 
      get 
      { 
       if (string.IsNullOrEmpty(this.GlobalResourceSetName)) 
       { 
        return MyHelper.GetLocalLocalizedString(this.DisplayNameKey); 
       } 
       else 
       { 
        return MyHelper.GetGlobalLocalizedString(this.DisplayNameKey, this.ResourceSetName); 
       } 
      } 
     } 
    } 
} 

對於MyHelper,該方法可以是這樣的:

public string GetLocalLocalizedString(string key){ 
    return _resourceSet.GetString(key); 
} 

顯然,你將需要添加的錯誤處理,並有resourceReader成立。更多信息here

有了這個,你再與新的屬性裝飾你的模型,傳遞你想從價值資源的關鍵,這樣

[LocalizedDisplayName("Title")] 

然後Html.LabelFor將顯示本地化文字自動。

2

我想你將不得不重寫DataAnnotations屬性來使它們與數據庫資源提供者本地化。您可以從當前的繼承,然後指定其他屬性,如數據庫連接字符串以在從自定義提供程序獲取資源時使用。

+0

不幸的是,這不起作用,因爲DisplayAttribute是一個密封的類。即使我爲屬性執行我自己的實現,我也必須覆蓋Html擴展方法(例如Html.LabelFor)。 – slfan 2011-03-09 13:36:58

+0

我做了進一步的調查:我可以派生自DisplayNameAttribute具有可重寫的屬性DisplayName。最後,我使用T4模板來生成Resources類,因爲我不必實現所有數據註釋屬性。 – slfan 2011-03-10 15:15:10

相關問題