Introduction
Here I will discuss how to develop multilingual and localized pages in .NET web applications. The main problem with the multilingual application is reset the current culture, language each time page is postback because it may reset to the default language/culture. I will also discuss use of resource files for multilingual application and also approaches to localize images.
Description
Let us start this exercise in steps.
- Create your own base page class: The problem with multilingual application as I discussed earlier is that it might reset the culture back to the default during page postback. To tackle with this issue .NET provides us a method which is part of page life cycle to initialize culture. So we can write our own class inherited from System.Web.UI.Page class and override its InitializeCulture method as follows:
protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(CurrentLoggedinUser.PreferredCulture);
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(CurrentLoggedinUser.PreferredCulture);
base.InitializeCulture();
}
Now override each of your aspx page with your own class instead of Page class. And it will reset the current culture as per your requirement.
- Using resource file: Resource files are the .resx extension file where you can keep content of your web pages to choose according to the language. You should keep 1 resource file for each language your application support. Now the question is how to pick values from these resource files, no problem, its jus matter of couple of lines of code:
ResourceManager rm =new ResourceManager(“Name of resource file”,
Assembly. GetExecutingAssembly());
Label1.Text=rm.GetString(“key1”);
To avoid few compile time error in above code add following namespace in your code
Using System.Resources;
Using System.Reflection;
- Localizing Images: For localizing images you can choose any one of two approaches. First keep of name of all images in the resource file and access image path like this:
imageButton1.ImageUrl= rm.GetString(“imagepath1”);
Other approach which I prefer is to keep all images of one language in one folder and keep name of that folder in your resource file but remember to keep same name for a image in all language.
imageButton1.ImageUrl= rm.GetString(“ImageFolder”) +”LoginImage.jpg”;
Summary
Here we have discussed about creating localized pages in .NET application. We discussed that how to set culture in each page trip. Then we discussed how to pick values from resource file and the we discusssed approaches for localizing images of your application. Hope it helps. Thanks.