Nov 30 2009

Client side localization in ASP.NET using jQuery

Category: NovoGeek @ 19:01

Localization is a very important feature required in medium-large scale business applications. As always, ASP.NET makes developers life easy by providing inbuilt localization mechanism. Using resource files, all the elements in a web page can be localized.

However, if you are building a rich client side app using JavaScript/jQuery, you may need to fetch error messages and other strings from locale specific external file, without post back. In such cases, jQuery localization plugins come to rescue. Below are some of the best jQuery plugins, which help in localization:

  1. http://keith-wood.name/localisation.html
  2. http://codingwithcoffee.com/?p=272
  3. http://sundaymorning.jaysalvat.com/ 

The third one is cool with integrated Google translation API,  The second plugin is used by jqGrid & other plugins for localization. However, I really loved the first one - Keith wood's plugin, which gives a basic but powerful localisation features. All it does is, make synchronous call to the server and load locale specific JS file, which will override the variables of your base file. When you use custom events to change localized messages, the first one is the best, owing to its simplistic nature.

The question now is, how to get the UI culture of user's browser on page load.

Though the plugin is expected to do this, somehow, this is a missing feature. But you need not worry, as ASP.NET does this easily for you.In the "Session_Start" event of global.asax, just use this code:

Response.Cookies("UICultureCookie").Value = Request.UserLanguages(0)

This stores the first preferred UI culture of user's browser in a cookie. Using the information in this cookie is pretty simple using jQuery's cookie plugin. Just say:

var clientCulture = $.cookie("UICultureCookie");
$.localise('JavaScript/Constants/constants', { language: clientCulture }); 

That's it!  Now even your client side messages in ASP.NET can be localized, without postback, using the power of jQuery.

P.S:  I didn't write much about how to use these plugins, as their home pages have clear documentation & demos, which are self explanatory.

Tags:

blog comments powered by Disqus