Friday, March 6, 2015

Globalization and Localization in ASP.Net MVC 4

Introduction
In simple step I will show you to make you application globalize and localize in MVC 4.

I am writing this article because I found that there are not good and clean example of Globalization and Localization and many developer wont get any proper output from searching on Google . If you go hunting for Globalization and Localization for ASP.NET Webforms then you will get many cool example on this.

I to wrote Globalization and Localization in ASP.NET Webforms here is URL you can have a look at it: What is Globalization and Localization in ASP.Net.

Before starting let's have look at definition of globalization and localization below.

What is Globalization and Localization?

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 to make our application behave depending on the current culture and locale. These two things go together.

Getting Started
Create MVC application

In Visual Studio 2013 select "File" from the menu and inside that select Project and then a New Dialog will popup with the name New project.

Inside that select Templates then select Visual C# and then inside that select web then select ASP.NET MVC 4 Web Application. Name your project "MvcLocalization" and then click OK.

MvcLocalization

After this let's start with adding a resource to your application.

Before adding a resource I am will just create a folder named “LocalResource” and inside this I will add a resource.

LocalResource

Now to add the resource
  • The Main Resource should be “Resource.resx”.
  • For the English you can add "Resource.en-GB.resx".
  • For Marathi you can add "Resource.mr-IN.resx".
  • For Hindi you can add "Resource.hi-IN.resx".
  • For Arabic you can add "Resource.ar-SA.resx".
For adding the resource just right-click on the LocalResource folder then for inside what we just added select Add and then New Item.

New Item

A New Dialog will popup with name the Add New Item.

New Dialog

Inside the new dialog at the right side is a search box, type resource.

Resource

Then I will name my first resource file “Resource.resx”.

In a similar way we will add all other resources with the given names as above.

After adding all the resources your LocalResource folder will look as in the following snapshot.

LocalResource folder

1. Add some data
Let us add some data to these files. Open "Resource.resx".

add some data

Then just check the Access Modifier dropdownlist and make it Public.

Add a name under the "Resource.resx" Filename column and keep the Value column blank as in the following:

Value column

Save and close Resource.resx.

2. Open "Resource.en-GB.resx"
Add a name under the "Resource.en-GB.resx" filename and the value that you want to display in the value field.

Resource page

3. Open Resource.hi-IN.resx
Add a name under the "Resource.hi-IN.resx" filename and the value that you want to display in the value field.

value field

4. Open "Resource.mr-IN.resx"
Add a name under the "Resource.mr-IN.resx" filename and the value that you want to display in the value field.

display in the value field

5. Open "Resource.ar-SA.resx"
Add a name under the "Resource.ar-SA.resx" filename and the value that you want to display in the value field.

Add a name

Adding Model and Attribute to Properties. 
Now add a model with the name “Userdetails.cs” and then add a display attribute with the name similar to the resource “Name” column and then add ResourceType = typeof(Resource).
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using MvcLocalization.LocalResource;  
  7.   
  8. namespace MvcLocalization.Models  
  9. {  
  10.     public class Userdetails  
  11.     {  
  12.         [Display(Name = "FirstName", ResourceType = typeof(Resource))]  
  13.         public string FirstName { getset; }  
  14.   
  15.         [Display(Name = "LastName", ResourceType = typeof(Resource))]  
  16.         public string LastName { getset; }  
  17.     }  
  18.          }   
Adding custom class with name CultureHelper.cs
Now after completing the model now add a class with the name “CultureHelper.cs” in the new folder “Helper”. This class sets the Culture with the use of threading.

CultureHelper

Here is a code snippet of the CultureHelper class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.SessionState;  
  6. using System.Threading;  
  7. using System.Globalization;  
  8.   
  9. namespace MvcLocalization.Helper  
  10. {  
  11.     public class CultureHelper  
  12.     {  
  13.         protected HttpSessionState session;  
  14.   
  15.         //constructor   
  16.         public CultureHelper(HttpSessionState httpSessionState)  
  17.         {  
  18.             session = httpSessionState;  
  19.         }  
  20.         // Properties  
  21.         public static int CurrentCulture  
  22.         {  
  23.             get  
  24.             {  
  25.                 if (Thread.CurrentThread.CurrentUICulture.Name == "en-GB")  
  26.                 {  
  27.                     return 0;  
  28.                 }  
  29.                 else if (Thread.CurrentThread.CurrentUICulture.Name == "hi-IN")  
  30.                 {  
  31.                     return 1;  
  32.                 }  
  33.                 else if (Thread.CurrentThread.CurrentUICulture.Name == "mr-IN")  
  34.                 {  
  35.                     return 2;  
  36.                 }  
  37.                 else if (Thread.CurrentThread.CurrentUICulture.Name == "ar-SA")  
  38.                 {  
  39.                     return 3;  
  40.                 }  
  41.                 else  
  42.                 {  
  43.                     return 0;  
  44.                 }  
  45.             }  
  46.             set  
  47.             {  
  48.   
  49.                 if (value == 0)  
  50.                 {  
  51.                     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");  
  52.                 }  
  53.                 else if (value == 1)  
  54.                 {  
  55.                     Thread.CurrentThread.CurrentUICulture = new CultureInfo("hi-IN");  
  56.                 }  
  57.                 else if (value == 2)  
  58.                 {  
  59.                     Thread.CurrentThread.CurrentUICulture = new CultureInfo("mr-IN");  
  60.                 }  
  61.                 else if (value == 3)  
  62.                 {  
  63.                     Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar-SA");  
  64.                 }  
  65.                 else  
  66.                 {  
  67.                     Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;  
  68.                 }  
  69.   
  70.             Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;  
  71.   
  72.             }  
  73.         }  
  74.     }  
  75. }  
After adding CultureHelper now we are moving to the Controller.

Adding Controller

In this part we will add 2 Controllers.
  1. BaseController

    We use BaseController in MVC that is inherited by all other controllers. In BaseController, we write common code that can be used in all the pages, for example by setting the language in the current thread for a multilingual site.
  2. HomeController

    This Controller will inherit BaseController.
To add a Controller just right-click on the Controller folder and select Add then inside that select Controller.

BaseController

BaseController

Here is a code snippet of BaseController.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcLocalization.Helper;  
  7.   
  8. namespace MvcLocalization.Controllers  
  9. {  
  10.     public class BaseController : Controller  
  11.     {  
  12.         protected override void ExecuteCore()  
  13.         {  
  14.             int culture = 0;  
  15.             if (this.Session == null || this.Session["CurrentCulture"] == null)  
  16.             {  
  17.          
  18.             int.TryParse(System.Configuration.ConfigurationManager.AppSettings["Culture"], out culture);  
  19.             this.Session["CurrentCulture"] = culture;  
  20.             }  
  21.             else  
  22.             {  
  23.                 culture = (int)this.Session["CurrentCulture"];  
  24.             }  
  25.             // calling CultureHelper class properties for setting  
  26.             CultureHelper.CurrentCulture = culture;  
  27.   
  28.             base.ExecuteCore();  
  29.         }  
  30.   
  31.         protected override bool DisableAsyncSupport  
  32.         {  
  33.             get { return true; }  
  34.         }  
  35.   
  36.     }  
  37. }  
HomeController

HomeController

Here is a code snippet of HomeController.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcLocalization.Helper;  
  7. using MvcLocalization.Models;  
  8.   
  9. namespace MvcLocalization.Controllers  
  10. {  
  11.     public class HomeController : BaseController  
  12.     {  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             return View(new Userdetails());  
  17.         }  
  18.   
  19.         public ActionResult ChangeCurrentCulture(int id)  
  20.         {  
  21.             //  
  22.             // Change the current culture for this user.  
  23.             //  
  24.             CultureHelper.CurrentCulture = id;  
  25.             //  
  26.             // Cache the new current culture into the user HTTP session.   
  27.             //  
  28.             Session["CurrentCulture"] = id;  
  29.             //  
  30.             // Redirect to the same page from where the request was made!   
  31.             //  
  32.             return Redirect(Request.UrlReferrer.ToString());  
  33.         }  
  34.     }  
  35. }  
After this we will work on View.

We will first work on _LoginPartial.cshtml because we will add a link button on this page to display it on all pages of the website / application. 

_LoginPartial.cshtml code snippet
  1. @using System.Globalization  
  2. @using MvcLocalization  
  3. @using System.Threading;  
  4. @if (Request.IsAuthenticated)  
  5. {  
  6.     <p>  
  7.         Hello, @Html.ActionLink(User.Identity.Name, "ChangePassword""Account",   
  8.         routeValues: null,  
  9.         htmlAttributes: new { @class = "username", title = "Change password" })!  
  10.   
  11.         @Html.ActionLink("Log off""LogOff""Account")  
  12.     </p>  
  13. }  
  14. else  
  15. {  
  16.     <ul>  
  17.         <li>@Html.ActionLink("Register""Register""Account",  
  18.         routeValues: null, htmlAttributes: new { id = "registerLink" })</li>  
  19.   
  20.         <li>@Html.ActionLink("Log in""Login""Account",  
  21.         routeValues: null, htmlAttributes: new { id = "loginLink" })</li>  
  22.     </ul>  
  23. }  
  24.   
  25. <ul style="margin-top:10px;">  
  26.     @{  
  27.         CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;  
  28.         
  29.         <li><a href="/Home/ChangeCurrentCulture/0">English</a></li>  
  30.         
  31.         <li><a href="/Home/ChangeCurrentCulture/1">Hindi</a></li>  
  32.                   
  33.         <li><a href="/Home/ChangeCurrentCulture/2">Marathi</a></li>  
  34.           
  35.         <li><a href="/Home/ChangeCurrentCulture/3">Arabic</a></li>  
  36.     }  
  37. </ul>  
Here is the link from where the user will be able to change his website Language.

As we have decided for what language we will use that code.

English :- 0 | Hindi:- 1 | Marathi :- 2 | Arabic :- 3

code

When the user clicks on this link it will call the Home Controller ChangeCurrentCulture Action result and it will pass an id to it.

According to that CultureHelper will get input and it will set the Culture for the page.

Adding View for HomeController

For adding a View just right-click anywhere inside HomeController and select Add View.

Add View

After clicking Add View a new dialog will popup with the name Add View. Inside that you need to select:
  • View engine: Razor.
  • Model Class: Userdetails.
  • Scaffold template: Create.
  • Use a layout or Master page: Check this Property.
Clicking Add View

And click on the Add button.

Add click

When adding a view using a Scaffold template all the code for the view will be generated.

Index.cshtml code snippet.
  1. @model MvcLocalization.Models.Userdetails  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. @using (Html.BeginForm()) {  
  10.     @Html.ValidationSummary(true)  
  11.   
  12.     <fieldset>  
  13.         <legend>Userdetails</legend>  
  14.   
  15.         <div class="editor-label">  
  16.             @Html.LabelFor(model => model.FirstName)  
  17.         </div>  
  18.         <div class="editor-field">  
  19.             @Html.EditorFor(model => model.FirstName)  
  20.             @Html.ValidationMessageFor(model => model.FirstName)  
  21.         </div>  
  22.   
  23.         <div class="editor-label">  
  24.             @Html.LabelFor(model => model.LastName)  
  25.         </div>  
  26.         <div class="editor-field">  
  27.             @Html.EditorFor(model => model.LastName)  
  28.             @Html.ValidationMessageFor(model => model.LastName)  
  29.         </div>  
  30.   
  31.         <p>  
  32.             <input type="submit" value="Create" />  
  33.         </p>  
  34.     </fieldset>  
  35. }  
  36.   
  37. <div>  
  38.     @Html.ActionLink("Back to List""Index")  
  39. </div>  
  40.   
  41. @section Scripts {  
  42.     @Scripts.Render("~/bundles/jqueryval")  
  43. }  
Now we have completely configured the code. Now we just need to run the application and check it.

Complete view of page

It's taking the default culture, English, when it loads the first time. 

load first time

Here is the link we added.

added

Let's check it by clicking on Hindi first:

check clicking

Now to click on Marathi.

click on Marathi

And finally click on Arabic.

click on Arabic

DONE!!!!


No comments:

Post a Comment