Asp.net-Mvc

帶有 DisplayAttribute 和自定義資源提供程序的 ASP.NET MVC 3 本地化

  • August 8, 2014

我使用自定義資源提供程序從數據庫中獲取資源字元串。這適用於 ASP.NET,我可以將資源類型定義為字元串。MVC 3 中模型屬性的元數據屬性(如

$$ Range $$,$$ Display $$,$$ Required $$需要 Resource 的類型作為參數,其中 ResourceType 是生成的 .resx 文件的程式碼隱藏類的類型。

   [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 類是密封的。對於驗證屬性,不存在相應的類。

您可以擴展 DisplayNameAttribute 並覆蓋 DisplayName 字元串屬性。我有這樣的東西

   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設置。更多資訊在這裡

有了這個,你然後用新屬性裝飾你的模型,傳遞你想要從中獲取值的資源的鍵,就像這樣

[LocalizedDisplayName("Title")]

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

我想出的最乾淨的方法是覆蓋DataAnnotationsModelMetadataProvider. 這是一篇關於如何做到這一點的非常簡潔的文章。

http://buildstarted.com/2010/09/14/creating-your-own-modelmetadataprovider-to-handle-custom-attributes/

引用自:https://stackoverflow.com/questions/4872309