1
我在我的應用程序中有managed to localize the view pages,但有主頁包含一些字符串。本地化ASP.NET MVC應用程序的母版頁中的字符串
看起來,母版頁中包含的字符串必須添加到每個頁面的資源文件中。這看起來很可怕。我如何優雅地本地化母版頁中的字符串?
我在我的應用程序中有managed to localize the view pages,但有主頁包含一些字符串。本地化ASP.NET MVC應用程序的母版頁中的字符串
看起來,母版頁中包含的字符串必須添加到每個頁面的資源文件中。這看起來很可怕。我如何優雅地本地化母版頁中的字符串?
如果你不想與訪問修飾符一塌糊塗,你可以做一個幫手來簡化你必須按順序訪問資源編寫代碼文件是這樣的:
public static class LocalizationHelper
{
public static string Localize(this HtmlHelper helper, string key)
{
var resourceObject = helper.ViewContext.HttpContext.GetGlobalResourceObject("NameOfResourceFileClass", key);
if (resourceObject == null)
{
// i don't recommend throwing the Exception class, I'd define my own Exception type here
throw new Exception(String.Format("Resource key '{1}' could not be found in Resource class '{0}'","NameOfResourceFileClass", key));
}
return resourceObject.ToString();
}
}
然後在你的.master ...
<%= Html.Localize("NameOfResourceKey") %>
您應該使用全局資源文件。
App_GlobalResources
asp.net文件夾My.Resources.Resource.MyText
(VB語法)創建資源文件Public
從源代碼訪問母版頁的資源:
<asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:ResourcesFileName, ResourcesName%>" />