Click here to Skip to main content
Licence CPOL
First Posted 11 May 2007
Views 97,414
Downloads 930
Bookmarked 75 times

Developing an ASP.NET page with MasterPage and Localization

By Michael Ulmann | 7 May 2008
The MasterPage is derived from UserControl and thus, does not support the method 'InitializeCulture()'; a bit more coding is required in order to make the ASP.NET MasterPage localizable.
2 votes, 5.1%
1
2 votes, 5.1%
2
2 votes, 5.1%
3
6 votes, 15.4%
4
27 votes, 69.2%
5
4.61/5 - 39 votes
4 removed
μ 4.28, σa 2.01 [?]

Introduction

While seeking on the internet for a solution to implement localization within an ASP.NET application using a MasterPage, I realized that a lot of people have got the same problem to solve. Unfortunately, I could not find a suitable solution thus, I intended to do my own implementation.

Background

The solution presented within this article uses the standard localization mechanism of the .NET framework.

Using the code

The published solution uses the Session object as storage for the currently selected culture. This will be initialized during the Session_Start method that is part of the global.asax file.

If a culture change is requested by the user, the MasterPage changes the stored culture in the Session object.

In a BasePage that inherits from Page, the method InitializeCulture is overridden and sets the appropriate culture information stored in the Session object to the current thread. Therefore, every Web Form needs to derive from this BasePage.

Let's start with the Global.asax file:

void Session_Start(object sender, EventArgs e) 
{
    //set english as default startup language
    Session["MyCulture"] = "en-GB";
}

Alternatively, the culture can be defined in the Web.config file with the key <globalization culture="en-GB" /> and then be processed and stored in the Session object from the Session_Start method.

The next step is the master page:

<%@ Master Language="C#" AutoEventWireup="true" 
           CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>[Smart-Soft - Masterpage with Localization Support]</title>
</head>

<body>
    <form id="theForm" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder" runat="server">
        </asp:contentplaceholder>
    </div>
    <div style="margin-top:20px;">
        <asp:LinkButton ID="btnSetGerman" runat="server" Text="Deutsch" 
           CommandArgument="de-CH" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>  
        <asp:LinkButton ID="btnSetEnglish" runat="server" Text="English" 
           CommandArgument="en-GB" OnClick="RequestLanguageChange_Click">
        </asp:LinkButton>
    </div>
    </form>
</body>
</html>

The buttons to change the culture can be either placed in the MasterPage directly, or in any embedded UserControl. In order to determine the requested language, the CommandArgument attribute of the LinkButton is used.

..And the code-behind of the master page:

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void RequestLanguageChange_Click(object sender, EventArgs e)
    {
        LinkButton senderLink = sender as LinkButton;

        //store requested language as new culture in the session
        Session["MyCulture"] = senderLink.CommandArgument;

        //reload last requested page with new culture
        Server.Transfer(Request.Path);
    }
}

The requested language, passed within the CommandArgument, is processed and stored in the Session object. Afterwards, the initially requested page will be reloaded on the server side.

Last but not least, the BasePage:

/// <summary>
/// Custom base page used for all web forms.
/// </summary>
public class BasePage : Page
{
    private const string m_DefaultCulture = "en-GB";
    
    protected override void InitializeCulture()
    {
        //retrieve culture information from session
        string culture = Convert.ToString(Session["MyCulture"]);

        //check whether a culture is stored in the session
        if (!string.IsNullOrEmpty(culture)) Culture = culture;
        else Culture = m_DefaultCulture;

        //set culture to current thread
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

        //call base class
        base.InitializeCulture();
    }
}

As mentioned above, the InitializeCulture method is overridden, and gets the stored culture from the Session object and assigns it to the currently running thread.

Remark: In this article, only the culture was mentioned. Of course, there is also the UI culture. But it is not of any further interest in this article since the handling is absolutely identical. For more information, please see the MSDN pages. :)

For a running example, download the Zip file above.

History

  • 11 May 2007 - First version released.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Michael Ulmann

Architect
Helvetic Solutions
Australia Australia

Member
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5
My company: www.helveticsolutions.com
Hopp Schwiiz Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionWebsite is localized, but how to I put querystrings on them to show different URLs? PinmemberJason P. Weber20:36 28 Jan '12  
QuestionThank you for providing such clear instructions and offering a downloadable source code PinmemberJason P. Weber8:13 23 Jan '12  
QuestionPS - Beautiful implementation PinmemberfitITOren5:30 6 Sep '11  
SuggestionWhy session and not cookies?? PinmemberfitITOren5:29 6 Sep '11  
GeneralRe: Why session and not cookies?? PinmemberMichael Ulmann18:41 10 Oct '11  
QuestionSuper great - what about using cookies for remembering for next time...? PinmemberfitITOren5:22 6 Sep '11  
Questionweb.config PinmemberSuici4:47 24 Jun '11  
AnswerRe: web.config PinmemberMichael Ulmann18:19 11 Aug '11  
GeneralLocalization Page(have issues) PinmemberKleen201111:16 13 May '11  
GeneralRe: Localization Page(have issues) PinmemberMichael Ulmann18:23 11 Aug '11  
GeneralMy vote of 5 PinmemberOmar Gamil0:38 26 Dec '10  
GeneralMy vote of 5 Pinmemberkimic14:59 4 Nov '10  
GeneralMy vote of 5 Pinmembergico22:09 13 Oct '10  
GeneralMy vote of 5 PinmemberKeith Barrow9:00 21 Sep '10  
GeneralGreat work! Pinmemberjonrandahl3:20 15 Sep '09  
GeneralMerci vielmal ;-) PinmemberDarkjo22:24 12 Aug '09  
GeneralRe: Merci vielmal ;-) PinmemberMichael Ulmann18:22 11 Aug '11  
Questionerror in localization using masterpage Pinmembermdazeemuddin2:53 31 May '09  
AnswerRe: error in localization using masterpage PinmemberMichael Ulmann3:06 31 May '09  
GeneralRe: error in localization using masterpage Pinmembermdazeemuddin5:37 31 May '09  
GeneralRe: error in localization using masterpage PinmemberMichael Ulmann17:05 3 Jun '09  
GeneralTerrible Code! PinmemberTV Mogul6:44 26 Apr '09  
GeneralRe: Terrible Code! PinmemberMichael Ulmann15:41 26 Apr '09  
Dear Bill,
 
I understand that you may be frustrated by the fact that you haven't understood how the .NET framework utilizes resources.
Have you by any chance thought about that you might have done something wrongly since you are obviously the only one experiencing this problem?
 
Basically, there are two ways you can use resources in a web application.
Firstly, you can have the resources organized on a per page/uc basis. That means that you need to place your resource file in the App_LocalResources folder using the same file name as the page/uc suffixed by ".resx".
Alternatively you may want to manage your resources in a central pool. In this case you would place them all in the App_GlobalResources folder in the web root. That would mean that every time you are referencing a resource in your code that you have to specify in which global resource file the resource is stored. E.g. <%$ Resources: PageTitles, DefaultTitle %>
Best practise would be to store resources on a per page/uc basis where resources are closely related to them. Common resources used in various places should be managed in the global resource pool.
 
Hence, if you try to use resources without properly specifying a resource repository the compilation fails.
 
I hope this helped eliminating your frustrations.
 
Cheers,
Michael

GeneralRe: Terrible Code! PinmemberTV Mogul1:30 27 Apr '09  
GeneralRe: Terrible Code! PinmemberTV Mogul1:49 27 Apr '09  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120210.1 | Last Updated 7 May 2008
Article Copyright 2007 by Michael Ulmann
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid