Click here to Skip to main content
15,879,239 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.80/5 (46 votes)
26 May 2014CPOL5 min read 263.6K   7K   55   26
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.

Image 1

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.

C#
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.

C#
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

C#
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:

Image 2

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.

Image 3

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.

Image 4

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

Image 5

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.

Image 6

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:

C#
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.

Image 7

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.

Image 8

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.

C#
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.

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

Let us now run the application and see the results.

Image 9

Image 10

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)


Written By
Architect
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[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionProblem with some Images Pin
Member 104120572-Jun-18 13:37
Member 104120572-Jun-18 13:37 
QuestionAsp.net FileUpload Control with Localizatin Pin
Member 1054457611-Apr-18 20:43
Member 1054457611-Apr-18 20:43 
QuestionGetString Pin
Member 1262577930-Mar-17 8:39
Member 1262577930-Mar-17 8:39 
QuestionMulti language Pin
Member 123808859-Mar-16 7:24
Member 123808859-Mar-16 7:24 
QuestionMultilingual website without Resource file handling Pin
Member 1222318623-Dec-15 1:07
Member 1222318623-Dec-15 1:07 
GeneralMy vote of 5 Pin
D V L6-Sep-15 1:47
professionalD V L6-Sep-15 1:47 
GeneralGreat Explanations Pin
MCY26-Aug-15 22:10
professionalMCY26-Aug-15 22:10 
BugThis doesn't work Pin
Member 1142070711-Aug-15 5:00
Member 1142070711-Aug-15 5:00 
GeneralRe: This doesn't work Pin
Jean Ferre17-Aug-15 22:47
Jean Ferre17-Aug-15 22:47 
GeneralRe: This doesn't work Pin
Member 1142070717-Aug-15 22:49
Member 1142070717-Aug-15 22:49 
QuestionNice article Pin
Sander Rossel4-May-15 2:22
professionalSander Rossel4-May-15 2:22 
QuestionMultilanguage support in Database Pin
harshal99926-Mar-15 19:27
harshal99926-Mar-15 19:27 
QuestionNice article Pin
Saineshwar Bageri19-Feb-15 21:32
Saineshwar Bageri19-Feb-15 21:32 
QuestionStrongly typed? Pin
lilkillabee219-Feb-15 4:01
professionallilkillabee219-Feb-15 4:01 
GeneralMy vote of 5 Pin
Debabrata_Das4-Feb-15 22:39
professionalDebabrata_Das4-Feb-15 22:39 
QuestionHow to change the language using language provide in drop down list Pin
Apoorv Agrawal17-Jan-15 7:17
Apoorv Agrawal17-Jan-15 7:17 
GeneralGood basics ! Pin
ultraman697-Jan-15 10:48
ultraman697-Jan-15 10:48 
QuestionI am not able to access MyResources.Resource Pin
Member 1133235429-Dec-14 18:50
Member 1133235429-Dec-14 18:50 
QuestionGreat Article, however Pin
Baaba Maal29-Dec-14 9:56
Baaba Maal29-Dec-14 9:56 
AnswerRe: Great Article, however Pin
Umesh Bhosale5-Aug-15 20:57
Umesh Bhosale5-Aug-15 20:57 
QuestionSimple Language Pin
dev4ever21-Dec-14 20:23
dev4ever21-Dec-14 20:23 
QuestionGood Article Pin
Mohammad A. Amer29-Oct-14 3:46
professionalMohammad A. Amer29-Oct-14 3:46 
Good Article, My vote of 5
GeneralGreat help. Pin
jetendramanpradhan23-Aug-14 19:29
jetendramanpradhan23-Aug-14 19:29 
QuestionResources are not recognized if in external DLL Pin
Xavier Fischer2-Jul-14 11:01
Xavier Fischer2-Jul-14 11:01 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh17-Jun-14 18:32
professionalRahul Rajat Singh17-Jun-14 18:32 

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

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