Click here to Skip to main content
15,881,172 members
Articles / Web Development / XHTML

Implement Multi Language Support for Client Side Validations in ASP.NET 3.5

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
13 Apr 2009CPOL2 min read 35.2K   629   19   1
This article demonstrates how to develop multi language page at server side as well as client side

Introduction

This article talks about how to develop a multilingual web page in Visual Studio 2008 and enable client script exposed alert messages based on respective language.

Background

A few days ago, I was working on my applications to enable them for multiple languages (English, French and Japanese) to address audiences of different regions.

Enabling an aspx page for multiple languages is very easy and for doing so, we need to maintain resource files (*.resx) for each and every language, and easily generate resource file(s).

To generate resource files, open aspx page in design mode, then go to Tools-->Generate Local resource.

Generatelocalres.JPG

This will create a meta resource key for all string values in a resource file and same entry inserted in markup, like:

XML
<asp:Label ID="lblcname" runat="server" Text="Customer Name: *" 
	meta:resourcekey="lblcnameResource1" />

Now we need to override InitializeCulture at the page level:

C#
protected override void InitializeCulture()
        {
            string culture = string.Empty;
            culture = Request.Form["ddlLang"];
            if (string.IsNullOrEmpty(culture)) culture = "Auto";
            UICulture = culture;
            Page.Culture = culture;
            if (culture != "Auto")
            {
                CultureInfo ci = new CultureInfo(culture);
                Thread.CurrentThread.CurrentCulture = ci;
                Thread.CurrentThread.CurrentUICulture = ci;
            }
        }
<pin>ddlLang is a dropdown that lists available languages.

But my focus is to develop multilanguage support for client side, so if JavaScript is popping up an alert, that should be in the respective language.

Using the Code

To implement the client side capabilities, I have created a resource file there under App_globalResources ASP.NET folder, and in each file I maintain JavaScript messages in the respective language. 

Like in Resource-fr-CA, the messageID and Messages are:

CustIDMessage         Identifiant client doit être entier    CustNameMessage     Nom du client ne peut pas être vide    NoErrorMessage       Aucune erreur trouvée   
   

Based on the selected culture, I am registering these messageIDs (CustIDMessage, CustNameMessage and NoErrorMessage) as JavaScript variables.       

C#
public void GetResourceString()
        {
            XDocument resDoc = new XDocument();
            StringBuilder sb = new StringBuilder();
            string resfile = Server.MapPath("~/App_GlobalResources/Resource-" + 
			ddlLang.SelectedValue.ToString()+".resx");
            resDoc = XDocument.Load(resfile);
            string MessageKey = null;
            string MessageString = null;
            Int32 Iteration = 0;

            foreach (var el in resDoc.Root.Descendants("data"))
            {
                MessageString = el.Value;
                MessageKey = ((System.Xml.Linq.XAttribute)el.FirstAttribute).Value;
                Iteration = Iteration + 1;
                string ss = string.Format("var {0} = '{1}';", 
					MessageKey, MessageString);
                sb.AppendLine(ss);
            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), 
					"jsMessages", sb.ToString(), true);
        } 

In the above code, I load the resource file by using Linq's XDocument and iterating the Xdocument to get MessageKey and MessageString. Here I create the script to register MessageKey as the variable name and MessageString as value.

After iterations, I register the resulting string as startup script.

On the aspx page, I have one button. On clicking on that button, it validates fields and pop up alert.

ASP.NET
<asp:Button  id="btnvalidate" runat="server" 
	OnClientClick="return validateEntry();" style="color: #008080;
       	font-weight: bold" Text="Validate" meta:resourcekey="btnvalidate" />  
<script language="Javascript">
function validateEntry()
    {
        var msg='';    
        var custid=document.getElementById('custID').value;
        var custname=document.getElementById('custName').value;   
        
        if(trim(custid)!='' && isNaN(trim(custid)))
        {
         msg+=CustIDMessage+'\n';        
        } 
                
        if(trim(custname)=='')
        {
         msg+=CustNameMessage;        
        }   
        
        if(msg=='')  
        {      
         alert(NoErrorMessage);
        }
        else
        {
         alert(msg); 
         }
         
         return false;         
    }
</script>

And if the selected language is Japanese, then the following script gets generated:

ASP.NET
 <script type="text/javascript">
//<![CDATA[
var CustIDMessage = '顧客IDの整数である必要があります';
var CustNameMessage = '顧客名を空白にすることはできません';
var NoErrorMessage = 'しないエラーが検出されました';
//]]>
</script> 

When I enter string in Customer Id and customer name is left blank, on clicking the validate button, I get the alert message in Japanese. 

Allert.JPG

Points of Interest 

This implementation is very easy and doesn't require hard coding in JavaScript. There may be issues due to some Unicode characters.

License

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


Written By
Team Leader
India India
Anees is working as Sr. Team Lead based in Delhi(India).He is Post graduated in Computer applications and science.

He is having around 11 years of design,analysis and coding experience in Sharepoint, ASP.NET, C#, VB.NET, SQL Server 2000/05, Reporting Services,Analysis Services,VB 6.0 and Crystal Reports.

Comments and Discussions

 
GeneralInteresting soltuion but... Pin
RawHid315-Apr-09 13:09
RawHid315-Apr-09 13:09 

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

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