Click here to Skip to main content
Click here to Skip to main content

Beginner's Tutorial on Globalization and Localization in ASP.NET MVC

, 26 May 2014
Rate this:
Please Sign up or sign in to vote.
In this article we will try to understand and implement Globalization and Localization in ASP.NET MVC.

Introduction

In this article we will try to understand and implement Globalization and Localization in ASP.NET MVC.

Background

Sometime back, I saw a TV commercial that said that "Even the smallest business can go multinational". This is very true specially in case of software business where guys operating from their store room provide services to users on the other side of the globe.

If we need our website to be designed in such a way that it caters to the need of users from across the planet, then perhaps it is a good idea to understand and implement Globalization and Localization in our application. In this article we will try to see what needs to be done to implement globalization and localization in an ASP.NET MVC application.

Before starting, let's get these two terms straight. Globalization is the process of designing the application in such a way that it can be used by users from across the globe (multiple cultures). Localization, on the other hand, is the process of customization that we do to have our application behave as per current culture and locale. These two things go together.

Note: This article will focus on globalization and localization in ASP.NET MVC. To know about localization and globalization in ASP.NET webforms please refer: Using Globalization and Localization in ASP.NET[^]

Using the code

Let us try to see how globalization and localization can be implemented in an ASP.NET MVC application by trying to develop a small sample application. This application will contain few static strings, few textboxes, Buttons and some validation error message strings.

Let us first implement this application without any localization and globalization support. Then we will see how we can implement localization and globalization. Let us start by creating a Demo model for this application.

public class Demo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Now let us add some DataAnnotation attributes to specify DisplayName and ErrorMessage.

public class Demo
{
    [DisplayName("Name")]
    [Required(ErrorMessage="Name is Required")]
    public string Name { get; set; }

    [DisplayName("Age")]
    [Required(ErrorMessage = "Age is Required")]
    public int Age { get; set; }
}

Now let us create a simple controller which will have a simple create method which will let us save the model data into an in memory collection

public class HomeController : Controller
{
    private static List<Demo> list = new List<Demo>();

    public ActionResult Index()
    {
        return View(list);
    }

    [HttpGet]
    public ActionResult Create()
    {   
        return View();
    }

    [HttpPost]
    public ActionResult Create(Demo model)
    {
        if (ModelState.IsValid)
        {
            list.Add(model);
            return RedirectToAction("Index");
        }

        return View();
    }
}

And finally the View page for this:

Now if we run the application, we can see that the view is adding the Demo model in an in memory collection.

Now let is see what needs to be done to implement the globalization and localization in this application. Let us start by identifying what all needs to be changed with the user culture.

Now let us try to implement the globalization and localization in this application. The problem currently in this application is that all the display strings are hard coded in the application. So to implement the globalization, we first need to externalize them in form of resources and then using the appropriate version of resources based on selected culture.

To do this, Let us first create a simple class library that will contain the resource files.

Let us put all the hard coded string in the resource files inside this class library.

If we want to have these resources in multiple languages, we need to have the separate resource files corresponding to each version. To have the resources in hindi-Indian, we need a resource file Resource.hi-in.resx. The "hi" specifies the language and "in" specifies the locale. We can also create a resource file only for a specific language i.e. the locale specification is not needed Resource.hi.resx.

Now what we need to do is to change our application to use this resource files instead of hard coded values. For that, let us add a reference to this class library and the start using the resource files for strings. So our Model will now look like:

public class Demo
{
    [DisplayName(MyResources.Resources.Name)]
    [Required(ErrorMessage=MyResources.Resources.NameRequiredError)]
    public string Name { get; set; }

    [DisplayName(MyResources.Resources.Age)]
    [Required(ErrorMessage = MyResources.Resources.AgeRequiredError)]
    public int Age { get; set; }
}

Also, let us change the hard coded strings in the view also.

To test the changes, we need to set the default language of our browser to Hindi-Indian. Since the application will check the browser language preferences and then try to load the language and culture accordingly. let change the language preference for IE.

Now our browser is configured to use Hi-IN as the default language. One last thing we need to do in our application is to intercept the browser language settings and set the current threads CUlture and UICulture value to the preferred language. This can be done in number of places of request life cycle, lets do this in Application_BeginRequest for this example.

private void Application_BeginRequest(Object source, EventArgs e)
{
    HttpApplication application = (HttpApplication)source;
    HttpContext context = application.Context;

    string culture = null;
    if (context.Request.UserLanguages != null && Request.UserLanguages.Length > 0)
    {
        culture = Request.UserLanguages[0];
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }
}

Note: Most applications have an application-wide BaseController for various reasons. The above code can also be put in the BaseController's constructor and will have the same effect. There is also a declarative way of achieving the same results by specifying globalization element in System.web element of web.config.

<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"></globalization>  

Let us now run the application and see the results.

Note: The text is exact translated using an online tool. So hindi knowing readers will find them rather out of context for few UI elements.

Now we have a sample MVC web application that is capable of being displayed in English and Hindi. To sum up, it is important to understand that Resource file is the key to have globalization and localization. it is always a good practice to put all the internationalization related resource files in a separate class library. Also, We need separate resource file for each supported culture.

Finally, we should never trust users browser settings and system settings to get the culture specific information. It is always a good idea to provide the user an option to change the language and culture for the website and perhaps track them using cookies so that user doesn't have to select the preferred language every time.

Point of interest

There are few important things to be understood when we are targeting our website to multiple cultures. When we are targeting multiple cultures, we cannot assume anything about the structure and layout of web page. The reason these things are important is because translation for even small text in English could be very lengthy in other languages. So it is always a good idea to follow the standard guidelines when we implement globalization.

  • No absolute positioning of controls
  • Use fluid layout with forms
  • No absolute size of controls
  • Try to arrange controls in a table

History

  • 16 May 2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4
 
If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionResources are not recognized if in external DLL [modified] PinmemberXavier Fischer2-Jul-14 11:01 
AnswerArticle of the Day on Microsoft's site PinmvpRahul Rajat Singh17-Jun-14 18:32 
GeneralExcellent Article PinmemberSuchi Banerjee, Pune2-Jun-14 1:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 26 May 2014
Article Copyright 2014 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid