Multi-lingual web applications using ASP.Net 4
In this article I am going to demonstrate how easily you can develop multi-lingual web applications using asp.net. For the purpose of this demonstration, I am going to create a web page that is available in both English and Arabic languages.
The web page has the following controls
- text boxes for collecting name and description from the user,
- button for submitting the form
- dropdown list for selecting the user specified language
Once submitted, your will see thank you message as a JavaScript alert. Initially the page will be presented in English language. Using the dropdownlist in the top of the page, user can switch the language. At the end of this article, I will explain you how to make it auto so that the language will be displayed based on user browser settings.
Ok, let me stop the theory and demonstrate this.
I have Visual Studio 2010 installed. This demonstration is performed on VS 2010 installed in Windows 2007 64bit.
Open visual studio, then go to file -> new -> Project. The new project dialog will appear. Select Visual C#(or your preferred language) from the left side menu. From here all my explanation is based on C#, but for any other .Net languages, the steps will be similar. Under the web category, select ASP.Net Empty web application, specify a name for your project and choose a suitable path.
Click ok to create your project. Since I selected empty project, there will not be any aspx pages created for me. The solution explorer will look similar to follows
In the solution explorer, right click the project, then select Add -> New Item. The new item dialog appears, select Web Form, give its name as Default.aspx, click on add button. The new page will be created.
Add 2 labels, 2 textboxes ,one dropdownlist and one button. The text for labels are changed to Name : and Description : respectively. The Dropdownlist is populated with 2 list items, one with text english having value en-US and second with text Arabic having value ar-BH. (These values can be changed according to your language preferences) The following is the output of the page in the browser.
Now I am going to create local resource file for the page. Open default.aspx in visual studio, click on the content area (make sure the focus is in the content area). From the top menu bar, select Tools and then click on generate Local Resource.
* note: If the generate local resource item is disabled in the menu, make sure you have the focus in the page content area or in any controls.
You will see App_LocalResources folder is added to the project and under it, you can see Default.aspx.resx. This is an xml file that contains defenitions for localizable elements in the page. Basically it is a XML file. In the solution explorer, double click on Default.aspx.resx, Visual Studio will open the file in tabular format. The sample output will look as follows.
The details here are self-explanatory. If you add further modifications to the page, you can easily regenerate the resource file again by clicking tools -> generate local resources.
Now I am going to generate the resource file for the other Language, in my case Arabic. Right click Default.aspx.resx file and copy it. Click on App_LocalResources and paste the copied file. Rename the copied file to Default.aspx.ar.resx . Double click on default.aspx.ar.resx and change some values to Arabic(I used google translator to translate from English to Arabic). Enter the values with the translated text in the value column for the items. Sample screenshot is as follows.
note that the list item values(en-US and ar-BH) are not translated as they will be used to decide the page language in the backend.
Since English is left to right language and Arabic is right to left, the direction attribute needs to be changed for each language. This is not a local resource as it needs to reflect in all the pages of my application. Here we need to use Global Resources.
So I am going to create global resources for the project. From the solution explorer right click the project, select add -> “add asp.net folder” -> App_GlobalResources
App_GlobalResources folder will be added to the solution. Right click the App_GlobalResources folder and click add new item. Select the “Resources file” from the template and give it a proper name(I named it GlobalMessages.resx).
Open GlobalMessages.resx in visual studio. Add one resource with Name direction having value ltr. Copy and paste the GlobalMessages.resx to the App_GlobalResources folder and rename it to GlobalMessages.ar.resx . Open GlobalMessages.ar.resx in visual studio and change the value for direction to rtl. Additionally I added a resource named message to the GlobalMessages.resx with value as a thank you message(Also I translated this to aratic in GlobalMessages.ar.resx). The global resource file looks like
Now I need to set the value of the dir attribute of the body tag to be updated from the resource file. To do that, use the following code in the markup.
<body dir='<asp:Literal runat="server" Text='<%$Resources: GlobalMessages, direction %>'></asp:Literal>'>
The code is self-explanatory. I am setting the literal value with the value from Resource file GlobalMessages.resx (or GlobalMessages.ar.resx) and setting the literal value to the dir attribute of the body tag. The expected output is
The next thing I would like to set the culture for the page. Since the user culture will be decided using the selection from the dropdownlist we added to the page.According to ASP.Net page lifecycle, to set the page culture of a page you need to use the override InitializeCulture(). Page_Load and button click events etc appearing after InitializeCulture().Also from the event, you will not be able to access the server control values. But you can access the Request object to get the posted values. I enabled autopostback to true for the dropdown list so that the language will change instantly. Also I made the ClientIDMode for the control to static to make sure I get fixed name in the Request collection.
protected override void InitializeCulture()
{
if (Request.Form["language"] != null)
{
String selectedLanguage = Request.Form["language"];
UICulture = selectedLanguage;
Culture = selectedLanguage;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(selectedLanguage);
}
base.InitializeCulture();
}
The code is self-explanatory. It is setting the current thread’s culture and UICulture to the dropdown’s selection. Since Autopostback is enabled for the dropdownlist, the above code will be executed when the dropdownlist values changes.
That’s it. Now run the page. It will give you the following output in the browser.
Now from the dropdownlist select the Arabic and see the output as follows
Now when the user click the submit button, I would like to show a thank you message to the user reading from global resources.
Add the onclick event handler to the submit button. The code for the button click is as follows.
protected void Button1_Click(object sender, EventArgs e)
{
string msg = txtName.Text + ", " + GetGlobalResourceObject("GlobalMessages", "message").ToString();
ClientScript.RegisterStartupScript(this.GetType(), "myScript", "alert('" + msg + "');", true);
}
The code is appending the user entered name with the message value from GlobalMessages and registering an alert message to display this to the page.
The output is as follows.
Just change the language dropdown from English to Arabic and submit the form. You will see the following output.
Similar to GetGlobalResourceObject, there is a method available GetLocalResourceObject that reads the data from the local resource file. You can define your page specific messages to the local resource file and the message shared among the entire application needs to be placed inside GlobalResource file.
As I specified in the start of this article, sometimes you need the page to be rendered according to the user browser settings. This can be achieved by specifying culture and uiculture values to auto.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MultiLingualSample.Default" meta:resourcekey="PageResource1" culture="auto" uiculture="auto" %>
Once you define this(don’t forget to remove the initializeCulture() code from the code behind file), if you want to see the Arabic page, set the browser settings to the specific language.
If you want the above application in zipped format as email, please post your email id below and I will send it.