Globalization in ASP.Net MVC 3

Vivek picture Vivek · Apr 1, 2011 · Viewed 15.9k times · Source

I am trying to achieve globalization/localization in my MVC 3 application. I don't want different Views for each language. Please suggest how I can proceed. Any supported links/URLs will be of great help.

Answer

Martin Booth picture Martin Booth · Apr 1, 2011

You localize it in the same way as any other application like this:

  1. Create a folder, call it e.g. Resources
  2. Right click the folder and add class... choose resource file. Call it anything you like e.g. Strings.resx
  3. Under the properties of file, change Custom Tool to be PublicResXFileCodeGenerator
  4. Populate the Resource file with Translation key and value pairs (this will be the default translation)
  5. Create other resources with the name of the culture they're for in this format: {name}.de.resx e.g. Strings.de.resx
  6. (This is for Razor) crack open the web.config in the Views folder and add this to /configuration/system.web.webPages.razor/pages/namespaces: <add namespace="Resources" /> (assuming resources is the name of the folder you created the resources in and you haven't changed the default namespace on the resouce files themselves). This step means you don't have to fully qualify the resource classes in your views each time you want to reference a translation.
  7. Use the translations in place of text in your views like with the following code:

    @Strings.MyString
    

Strings will be automatically translated in the view depending on CultureInfo.CurrentCulture but this is not set automatically for you

You will need to change the CurrentCulture (potentially in Application_BeginRequest). How you do this is up to you, it could be a route value which sets it or you can read the user's browser language

You can find a list of the user's prefered languages (in order) in HttpContext.Current.Request.UserLanguages.