Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using Localization in ASP.NET

0.00/5 (No votes)
19 Feb 2008 1  
Outlines two useful methods for implementing localization in ASP.NET

This article is originally posted on my blog.

If you've designed, developed or worked on websites recently, you have probably come across the topic of localization. In this article, I'll show you how to implement localization in your Visual Studio .NET projects.

Most of us blanch at the idea of tailoring our pages to localize in multiple languages. The hard part of localization is, of course, the localizing. However, translating static labels and site content can be as easy as asking your user base to help. Good news though, once you've got that covered, the implementing is the easy part!

In this article, I'm going to focus on two ways of implementing localization in your .NET projects (and how to let your users choose). The first way is the "easy" way but might prove daunting in the long-term for large-scale websites. The second way is by grouping and scaling-down the amount of files to tend to. No way is best and I'll leave it up to you to decide which is better for your project.

Method 1: Using Generated Resource Files

Visual Studio .NET makes it easy to use localization by using its designer and tools. Let's see how it's done.

First, create a new website project.

I am using Visual Studio .NET 2008, but it will be similar no matter what version you're using.

Then, design a fairly simple webpage with a few label controls and a button control. One label will be a localized text label and the other will show what culture we're currently set to. The button will let us switch to a predefined culture.

Now, go to Tools and click 'Generate Local Resource.' This will create a corresponding Default.aspx.resx resource file for your webpage in the App_LocalResources folder. If you add more controls to the page, you must generate a local resource again. Note: Controls removed from the page will still show up in the resource file. Make sure to clean the resource file if you have deleted controls.

If you noticed, in the Source of your Default.aspx file, the attribute meta:resourcekey was added to your controls. The attribute value corresponds to the resource file control names (e.g. meta:resourcekey="Label1Resource1" corresponds to "Label1Resource1" and all its properties in the Default.aspx.resx file).

Now that we've generated a resource file, we can proceed to create a localized resource file. For a list of accepted cultures, check out this list. You can localize your project on a page-by-page basis or a global basis. For more information, see MSDN's How To: Set the Culture and UI Culture for ASP.NET Web Page Globalization.

We're going to localize on the page basis. In the Page directive, change the following attributes (from the default 'auto'): UICulture="es" culture="es-MX". Espanol will be our test culture. Your page directive should look something like this:

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" culture="es-MX"
meta:resourcekey="PageResource1" uiculture="es" %>

Now, let's localize! Right-click Default.aspx.resx and copy it. Paste it in the same folder and rename it to Default.aspx.es.resx. Change Label1Resource1.Text to 'A localized string in Espanol'.

Let's see what happens. Right-click Default.aspx and click View in Browser. Voila! We can see that the label's text has changed to the Spanish localized text.

Remember that you can use the Web.Config or Page method to also set the culture based on a browser's settings. But also realize that most people don't set it or might not have the correct setting. That's why we need to have a method for the user to choose a set language. Let's create a button that will change the culture back to US English programatically and display it.

Double-click the page background on the designer to create a Page_OnLoad event. In the event method, type in this code:

Protected Overrides Sub InitializeCulture()
If Request.Form("Button1") IsNot Nothing Then
Dim selectedLanguage As String = "en-US"
UICulture = selectedLanguage
Culture = selectedLanguage
Thread.CurrentThread.CurrentCulture = _
  CultureInfo.CreateSpecificCulture(selectedLanguage)
Thread.CurrentThread.CurrentUICulture = New  _
  CultureInfo(selectedLanguage)
End If
MyBase.InitializeCulture()
End Sub

Make sure to import System.Globalization and System.Threading. Let's see what happens now. Run your project again and you'll see that the label shows "Español (México)." Now click Change Culture. You'll see it says "English (United States)." Note: I changed my label to read "English label" via the resource file.

Congratulations! You've just learned how to use VS.NET's built-in Generate Local Resource tool to create a localized website.

Now let's take a look at a slightly different approach.

Method 2: Using A Global Resource File

If you're like me, the less files to manage the better. That's why I dug a little deeper and discovered how to use just one resource file to localize my websites. It requires a bit more work in the short-run but less work in the long run. Let's get started. Create a new page in our project called GlobalExample.aspx. Set it up so it looks like our previous page.

Now, right-click your project and go to "Add ASP.NET Folder" then App_GlobalResources. Create a new file called Lang.resx.

We've created a new resource file that will store all of our language strings. Let's add some. How about:

LBL_LOCALIZED_TXT with a value of "A global localized English string"

Now go back to GlobalExample.aspx and view the Source Code. For Label1's Text property, type in <%$ Resources: Lang, LBL_LOCALIZED_TXT %>. It should look like this:

<asp:label id="Label1" runat="server"
text="<%$ Resources: Lang, LBL_LOCALIZED_TXT %>" />

Here you see I've used a super-secret awesome shorthand for referencing our Lang resource file. If you to do the equivalent programatically, type this in the Code view:

Label1.Text = Resources.Lang.LBL_LOCALIZED_TXT

Kind of nice, huh? Strongly typed resource files makes it real easy to programatically add text to your controls. In theory, you could create an array with all your control IDs and their corresponding resource string names and assign them their values that way (e.g. a label named "lblTextInfo" and a resource string entry "lblTextInfo"):

Label1.Text = _
Resources.Lang.ResourceManager.GetString(Label1.ID)

If you view GlobalExample.aspx in a web browser, you'll see it works perfectly. Now, let's localize!

Create a duplicate of Lang.resx like we did before and rename it to Lang.es.resx. Type in something else for our label string. Go back to GlobalExample.aspx and add the two Page directives, UICulture="es" and Culture="es-MX". View the page in a browser. Voila! We've used one independent resource file as our container for localized strings.

Now, let's see how we switch it up a bit like our last example. Here's the best part. Copy and paste both the Page_Load and InitializeCulture routines from Default.aspx.vb into GlobalExample.aspx.vb (remember to import System.Globalization and System.Threading) and run the project!

Protected Overrides Sub InitializeCulture()
If Request.Form("Button1") IsNot Nothing Then
    Dim selectedLanguage As String = "en-US"
    UICulture = selectedLanguage
    Culture = selectedLanguage
    Thread.CurrentThread.CurrentCulture = _
        CultureInfo.CreateSpecificCulture(selectedLanguage)
    Thread.CurrentThread.CurrentUICulture = New  _
        CultureInfo(selectedLanguage)
End If
MyBase.InitializeCulture()
End Sub

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
Dim c As CultureInfo = CultureInfo.CurrentCulture

lblCulture.Text = c.NativeName
End Sub

You'll see that everything works just like it did in the last example. The only difference for this method is that we can have one resource file to hold all of our text strings. Maybe you want to organize it and create resource files for different kinds of text like "Links" and "Labels"; the possibilities are endless.

Final Thoughts

What have we learned? We learned about:

  • Using resource files
  • Changing a webpage or website's Culture
  • Programatically accessing a resource file
  • Programatically changing the current Culture

So which method is better? On one of my websites, I use Method 2. My dad uses Method 1 in his project at work and is very happy with the results. I don't advocate one method over the other, it's totally up to you. Maybe you have a small project so quickly generating resource files works just fine.

Happy coding and if you have suggestions or opinions, don't hesitate to comment!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here