在ASP.NET MVC应用程序的母版页中本地化字符串

时间:2009-07-18 12:02:37

标签: asp.net-mvc localization

我的应用程序中有managed to localize the view pages但有些母版页包含一些字符串。

主页中包含的字符串似乎必须添加到每个页面的资源文件中。这看起来很可怕。如何在母版页中优雅地本地化字符串?

2 个答案:

答案 0 :(得分:3)

如果您不想搞乱访问修饰符,您可以帮助简化您必须编写的代码以访问资源文件,例如:

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") %>

答案 1 :(得分:2)

您应该使用全局资源文件。

  1. 创建App_GlobalResources asp.net文件夹
  2. 为您的语言创建资源文件
  3. 将文件的访问修饰符设置为Public
  4. 使用My.Resources.Resource.MyText(VB语法)
  5. 访问所有资源

    alt text

    从主页的源代码访问资源:

    <asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:ResourcesFileName, ResourcesName%>" />