Localizing strings in master pages of ASP.NET MVC application

后端 未结 2 679
予麋鹿
予麋鹿 2021-01-07 10:22

I have managed to localize the view pages in my application but there are master pages which contain some strings.

It appears that the string contained in master pag

相关标签:
2条回答
  • 2021-01-07 10:49

    You should use a Global Resource file.

    1. Create the App_GlobalResources asp.net folder
    2. Create the resource files for your languages
    3. Set the Access Modifier of the files to Public
    4. Access all your resources with My.Resources.Resource.MyText (VB Syntax)

    alt text

    To access resource from source code of master page:

    <asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:ResourcesFileName, ResourcesName%>" />
    
    0 讨论(0)
  • 2021-01-07 11:04

    If you don't want to mess with the access modifier, you could make a helper to simplify the code you have to write in order to access the resource file, something like:

    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();
        }
    }
    

    Then in your .master...

    <%= Html.Localize("NameOfResourceKey") %>
    
    0 讨论(0)
提交回复
热议问题