戰地連結︰ Home My Flickr NBA.com About

2008年10月21日星期二

Switching Culture in an ASP.NET web app

Overview

In my previous blog post Globalization of ASP.NET with Resources File, I talk about my experience in providing multi-language support for an ASP.NET web app. In that example, the web app get the cultures from preference of user's browser. If a user wants to change the preferred culture, he/she has to change it in browser.
Is there a way to do it in the web app, so that user can change the culture by clicking a button / select from a dropdown? The answer is yes, and Michael Ulmann had done a very nice implementation of that by using "Master Page".

Reference

Developing an ASP.NET page with MasterPage and Localization

How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization (MSDN)

Steps

  1. Store the current culture name in a session variable.
  2. Make a new class (e.g. BasePage) inheriting System.Web.UI.Page, override method "InitializeCulture()". You cannot override this method in the MasterPage as the "MasterPage" class does not inherit System.Web.UI.Page, as  Example Code Snippet:

    protected override void InitializeCulture()

            {

                //retrieve culture information from session

                string culture = Convert.ToString(Session["MyCulture"]);

     

                Culture = culture;

               

                //set culture to current thread

                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);

                Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);

     

                //call base class

                base.InitializeCulture();

            }

  3. In the Master Page, make two Buttons with "Command Argument" set to "zh-TW" and "en-US" respectively. Assign the following method as their On-Click event:

    protected void LbnCulture_Click(object sender, EventArgs e)

    {

        // Change Culture

        Session["MyCulture"] = (sender as LinkButton).CommandArgument;
        // Reload Page to let new culture take effect

        Server.Transfer(Request.Path);

    }

  4. Create a new ASP.NET page (e.g. SamplePage) using the above Master Page, inherit "SamplePage" from "BasePage" (the class created in Step 1). Then you can test the buttons.

沒有留言: