Tip/Trick: Localization and Master Pages
Today, I found a great solution to create Multilingual Websites (Localization) with Master Pages.
The problem:
You want to create a Master Page for your website with a DropDownList for language changing,but, you can't override InitializeCulture().
The solution:
We can use a Master Page as our template, Default.aspx as a page which will set the Culture and UICulture of the page and User Controls for content.
First, we have to create our Master Page file with at least one ContentPlaceHolder.Then, we will create a Default.aspx page with a PlaceHolder:
Here is the code of Default.aspx page:
<%@ Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MySite.Default" Title="Untitled Page" %>
<asp:Content ID="pContent" ContentPlaceHolderID="dContent" runat="server"> <asp:PlaceHolder ID="phContent" runat="server"></asp:PlaceHolder> </asp:Content> |
Now we will code the Page_Load event of Default.aspx:
protected void Page_Load(object sender, EventArgs e) { phContent.Controls.AddAt(0, LoadControl("~/Pages/" + Request.QueryString["File"] + ".ascx")); } |
phContent is the PlaceHolderID.We want to load one control, then we load it to position 0.As you can see I used a QueryString("File") as a variable for our User Controls.Finally we have to override InitializeCulture():
protected override void InitializeCulture() { if (!String.IsNullOrEmpty(Request.QueryString["DisplayLang"])) { if (Request.QueryString["DisplayLang"] == "Auto") Session["DisplayLang"] = null; else Session["DisplayLang"] = Request.QueryString["DisplayLang"]; }
if (Session["DisplayLang"] == null) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.UserLanguages[0]); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); }
if (Session["DisplayLang"] != null) { string lang = Session["DisplayLang"].ToString(); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang.Remove(2, 3)); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang); } base.InitializeCulture(); } |
So far so good, now we can just use or create an UrlRewriter and use friendly url instead of QueryString.