【问题标题】:Localizing strings in master pages of ASP.NET MVC application本地化 ASP.NET MVC 应用程序母版页中的字符串
【发布时间】:2015-06-20 10:10:27
【问题描述】:

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

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

【问题讨论】:

    标签: asp.net-mvc localization


    【解决方案1】:

    如果您不想弄乱访问修饰符,您可以创建一个帮助程序来简化您必须编写的代码才能访问资源文件,例如:

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

    【讨论】:

      【解决方案2】:

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

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

      从母版页的源代码访问资源:

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

      【讨论】:

        猜你喜欢
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-22
        • 1970-01-01
        相关资源
        最近更新 更多