How to enable multiple language support in ASP.Net web site

The following is a sample solution to enable multiple language support in a ASP.Net web page developed using c#.

1. First create a class name as Base

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;

/// <summary>
/// Summary description for BasePage
/// 
/// Base page is the parent for all other pages. It sets the page to a specifi language culture.
/// 
/// </summary>
public class BasePage : System.Web.UI.Page
{
    public BasePage()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    /// <summary>
    /// Set current page language culture
    /// </summary>
    protected override void InitializeCulture()
    {

        string languageId = "0";
        HttpCookie language = Request.Cookies["language"];
        if (language != null)
        {
            languageId = language.Value;
            SetCulture(languageId, languageId);
        }

        base.InitializeCulture();
    }

    private void SetCulture(string lang, string cul)
    {
        try
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
            Thread.CurrentThread.CurrentCulture = new CultureInfo(cul);
        }
        catch
        {
        }
    }
}

2. Secondly, a web service method is created store the language setting based on users' choice

    [WebMethod(Description = "change current language", EnableSession = true)]
    public string ChangeLanguage(string selectLanguage)
    {
        CwSecurityTicket.EnsureTicket();

        string languageId = "0";
        HttpCookie language = new HttpCookie("language");
        languageId = selectLanguage;
        language.Value = selectLanguage;
        language.Expires = DateTime.MaxValue;
        HttpContext.Current.Response.Cookies.Set(language);
        return selectLanguage;
    }


3. Now we create a javascript function to call the web service and reload the current web page

function ChangeLanguage()
{

/*
Set to English

ws_MasterPage.ChangeLanguage("en-US",
OnSucceededLanguageChange, OnFailedLanguageChange);
*/
ws_MasterPage.ChangeLanguage("zh-CN",
OnSucceededLanguageChange, OnFailedLanguageChange);
}        
function OnSucceededLanguageChange(result)
{
  location.reload(true);          
}

function OnFailedLanguageChange(error)
{
  alert(error.get_message());
}

4. Add a language selector link to trigger the JavaScript. The javascript will call the web service to change the language option stored in the Cookie and reload the current page. When the current page is loaded, it will call the method in the BasePage to set the language culture.

5. Now we should use the language culture to decide what is the text to be displayed. The language culture can be used in the following manners: 

       Directly in the aspx page like following

                        <li><a href="/Help.aspx">
                            <asp:Literal ID=LiteralHelp
                                runat="server" Text="<%$Resources:MasterPageResource,Help%>" />
                        </a></li>

      In the code behind an aspx

        Image img2 = new Image();
        img2.AlternateText = Resources.MasterPageResource.LocalPrice;
 
    The language culture can also be used in Javascript. You need to add the language reference in the scritp manager like following
    <form id="MasterPageForm"
        runat="server">
        <asp:ScriptManager ID="ScriptManager1"
            EnableScriptLocalization="true"
            EnablePageMethods="true"
            runat="server">
            <Services>
                <asp:ServiceReference
                    Path="/ws_MasterPage.asmx" />
                <asp:ServiceReference
                    Path="/ProxyServices.asmx" />
            </Services>
            <Scripts>
                <asp:ScriptReference
                    Path="scripts/MS_Lang_Shared.js" />
                <asp:ScriptReference
                    Path="scripts/MS_Lang.js"
                    ResourceUICultures="en-CA,zh-CN" />
            </Scripts>
        </asp:ScriptManager>

You need to create the javascript resource file MS_Lang.js with different language settings like MS_Lang.zh-CN.js, MS_Lang.en-CA.js, MS_Lang.js. The the three resource files, resources should be defined like

In default page:
LoginPanel={
"Welcomeback":"Welcome back, ",
"Logout":"Logout",
"Login":"Login",
"ForgotPassword":"Forgot your password?"
};

In Chinese culture

LoginPanel={
"Welcomeback":"欢迎你,",
"Logout":"退出帐户",
"Login":"登陆",
"ForgotPassword":"丢失密码?"
};

Then in Javascript you can use the resources like following

document.getElementById('Result').innerHTML=
"<span id='Label2'>"+strMessage+"</span>"
+"<span id='Label3'>"+"<br/>"+"</span>"
+"<span id='Label4'>"
+"<a href='PasswordRecovery.aspx'>"
+ LoginPanel.ForgotPassword
+"</a>"
+"</span>"
;


Comments

Popular posts from this blog

Javascript Hosted on Google Drive Not Working Reliably

Newsmag Theme and External Featured Image

Responsive Web Design