Tuesday, November 4, 2008

Website Localization

The following pattern illustrates how to dynamically switch a website's culture. A master page should provide the list of supported cultures, the selected one being highlighted when the master page is first loaded:

HttpCookie cultureCookie = Request.Cookies["Culture"];
string cultureCode = (cultureCookie != null) ? cultureCookie.Value : "";
if (this.cboCulture.Items.FindByValue(cultureCode) != null)
{
this.cboCulture.SelectedValue = cultureCode;
}

The selected culture is preserved by a cookie, which is updated every time a new culture is chosen:

protected void cboCulture_SelectedIndexChanged(object sender, EventArgs e)
{
this.Response.Cookies.Add(new HttpCookie("Culture", this.cboCulture.SelectedValue));
this.Response.Redirect(this.Request.Url.OriginalString);
}


Finally, when the individual pages are initialized, the selected culture is applied. Ideally, this code would be factorized in a LocalizedPage, from which all of the website's pages should derive:

protected override void InitializeCulture()
{
HttpCookie cultureCookie = Request.Cookies["Culture"];
string cultureCode = (cultureCookie != null) ? cultureCookie.Value : "";
if (cultureCode != String.Empty)
{
this.UICulture = cultureCode;
this.Culture = cultureCode;
}
base.InitializeCulture();
}

No comments: