Monday, May 21, 2007

Localization in ASP .NET 2.0

I 'm going to explain How to implement multi lingual web forms in ASP .NET 2.0.
Let take it with a sample. Imagine we have a web form which user has to fill their personal information and save it to our database. Now, I want this web page to be multilingual.

So, First I just create a web page that I 'm going to have in English version. The web form name is "MultiLingualWebForm.aspx".

Then I have to add an special ASP .NET folder to my web site. So right click on web site, then Add ASP .NET Folder and choose App_LocalResources.

Now I have to add a new item in this folder like this:
R.C* on App_LocalResources --> Add New Item --> Resource File --> Set the name to "MultiLingualWebForm.aspx.resx"

Now a file will open up in Visual Studio .Net, I just try to add some Items in this Resource file and save the file.



Notice that the first part of name "WelcomeLable" is the Control name on the page, and the second part ".Text" is the property name of the control.

Then create another copy of this file with "MultiLingualWebForm.aspx.fr.resx" name.
The fr is telling that it 's the French version of that file.

And also another copy with name "MultiLingualWebForm.aspx.fa.resx" which fa is the international name of Farsi.


Then change all the values to it 's translation of target language:

Welcome ==> خوش آمديد
and so on...

Now, I 'm going to add some new attributes on my ASP controls. So in each of my Label controls I added a new tag called meta with a resourceKey property like this:


<asp:Label ID="WelcomeLabel" runat="server" Text="Label" meta:resourceKey="WelcomeLabel" ></asp:Label>

I add this to all the other Labels and also for those Buttons on my web form.
And I set two properties of my Page in my page directive.

Culture="auto:en-US" UICulture="auto"

Then I save the web page and run it.
So, to check out is it working or not? While you have your browser open, go to Tools menu then Internet Option, in the opening window go to Languages then add Farsi and French, bring up on of the to the first (it 's setting default language of your browser) then OK and OK again.

Now Refresh you page, you will see the translation of that page to your preferred language. OK That 's all.

Anyway, here is the code of my our sample you can download it.
http://www.tabatabaei.info/csharpsamples/MultiLingualWebForm.zip

1 comment:

Anonymous said...

Very handy - cheers!