Asp.net
如何在 mvc3 中對來自 @Html.LabelFor() 的內容進行本地化
我只是稍微擴展一下我的這個問題。
我的 MVC Web 應用程序中有我的App_LocalResources(我沒有在單獨的 dll 中)。
我在不同的裝配中有一個我的模型。在模型中,我有 2 個類
Country和City:public class Country: MyContainer { public City city {get;set;} } public class City { public CityName {get;set;} } public class MyContainer { public Cid {get;set;} }因此,在我的操作方法中,我創建並傳遞了一個國家對像作為我的視圖模型。
在視圖中我使用這個:
@Html.LabelFor(mdl=>mdl.City.CityName) @Html.LabelFor(mdl=>mdl.Cid)所以這很好用,帶有文本的標籤以英文呈現。
但是如何修改它以便它從我的 Web 應用程序中的資源文件中讀取文本?
您可以編寫自定義顯示屬性:
public class LocalizedDisplayNameAttribute : DisplayNameAttribute { public LocalizedDisplayNameAttribute(string key): base(FormatMessage(key)) { } private static string FormatMessage(string key) { // TODO: fetch the corresponding string from your resource file throw new NotImplementedException(); } }接著:
public class City { [LocalizedDisplayName("cityname")] public string CityName { get; set; } }您還可以查看以下本地化指南。它提供了範例屬性的完整實現。