Introduction
In this article, we will learn a step by step process to create a multilingual Web application using ASP.NET MVC. Multilingual means we can implement the website in multiple languages.
In today's world to grow customer interaction, everyone needs to implement this procedure in their applications.
Prerequisites
Note
Before going through this session, visit my previous articles related to ASP.NET MVC for better understanding.
Step 1
First, we need to add Resource File for different languages:
- Resource.resx - This is the default resource file for the English language.
- Resource.es.resx - This resource file is associated with the Spanish language.
- Resource.bn.resx - This resource file is associated with the Bengali language.
- Resource.or.resx - This resource file is associated with the Oriya language.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > Add New > Select Resource File under General > Enter File name > Add.
Set all the resource files Access Modifier to Public as mentioned in below image:
Step 2
In this step, we need to add a class file in the Model folder to configure field validation setup.
Go to Solution Explorer > Right Click on Modules folder > Add > Class > Enter Class name (SignUp.cs) > Add.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel;
-
- namespace MultilingualMVCApp.Models
- {
- public class SignUp
- {
-
- [Display(Name = "FirstName", ResourceType = typeof(Resource))]
- [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "FirstNameRequired")]
- public string FirstName { get; set; }
-
- [Display(Name = "LastName", ResourceType = typeof(Resource))]
- [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "LastNameRequired")]
- public string LastName { get; set; }
-
- [Display(Name = "Email", ResourceType = typeof(Resource))]
- [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "EmailRequired")]
- [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",
- ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "EmailInvalid")]
- public string Email { get; set; }
-
- [Display(Name = "Age", ResourceType = typeof(Resource))]
- [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "AgeRequired")]
- [Range(18, 60, ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "AgeRange")]
- public int Age { get; set; }
-
- [Display(Name = "Phone", ResourceType = typeof(Resource))]
- [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "PhnRequired")]
- [RegularExpression(@"^([0-9]{10})$", ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "PhnRange")]
- public string Phone { get; set; }
- }
- }
Code Description
Here, the typeof(Resource) is the file name for resources. All input fields have field validation for empty and if any input is not valid. Below, these namespaces are important for showing field names and validation messages to the user.
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel;
Step 3
In this step, we need to add another class to manage and setup language property & function that is based on language selection the all field text and validation text of input fields are translated accordingly.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > Class > Enter Class Name (LangTrans.cs) > Add.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Threading;
- using System.Web;
-
- namespace MultilingualMVCApp
- {
- public class LangTrans
- {
- public static List<Languages> AvailableLanguages = new List<Languages>
- {
- new Languages{ LangFullName = "English", LangCultureName = "en"},
- new Languages{ LangFullName = "Español", LangCultureName = "es"},
- new Languages{ LangFullName = "বাΰ¦ΰ¦²ΰ¦Ύ", LangCultureName = "bn"},
- new Languages{ LangFullName = "ΰ¬ΰ¬‘ΰ¬Ώΰ¬", LangCultureName = "or"}
- };
-
- public static bool IsLanguageAvailable(string lang)
- {
- return AvailableLanguages.Where(a => a.LangCultureName.Equals(lang)).FirstOrDefault() != null ? true : false;
- }
-
- public static string GetDefaultLanguage()
- {
- return AvailableLanguages[0].LangCultureName;
- }
-
- public void SetLanguage(string lang)
- {
- try
- {
- if (!IsLanguageAvailable(lang))
- lang = GetDefaultLanguage();
- var cultureInfo = new CultureInfo(lang);
- Thread.CurrentThread.CurrentUICulture = cultureInfo;
- Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
- HttpCookie langCookie = new HttpCookie("culture", lang);
- langCookie.Expires = DateTime.Now.AddYears(1);
- HttpContext.Current.Response.Cookies.Add(langCookie);
-
- }
- catch (Exception ex)
- {
-
- }
- }
- }
-
- public class Languages
- {
- public string LangFullName { get; set; }
- public string LangCultureName { get; set; }
- }
- }
Code Description
Here I added code with a description in a green comment mark "//" at one place for better and faster understanding.
Step 4
In this step, we add another class that acts as an inherit Controller, where BeginExecuteCore can be overridden. It is added for checking & set language each time any request execute.
Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > Class > Enter Class Name (MyCommonController.cs) > Add.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MultilingualMVCApp
- {
- public class MyCommonController:Controller
- {
- protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
- {
- string lang = null;
- HttpCookie langCookie = Request.Cookies["culture"];
- if (langCookie != null)
- {
- lang = langCookie.Value;
- }
- else
- {
- var userLanguage = Request.UserLanguages;
- var userLang = userLanguage != null ? userLanguage[0] : "";
- if (userLang != "")
- {
- lang = userLang;
- }
- else
- {
- lang = LangTrans.GetDefaultLanguage();
- }
- }
-
- new LangTrans().SetLanguage(lang);
-
- return base.BeginExecuteCore(callback, state);
- }
- }
- }
Code Description
Here I added code with a description in green comment mark "//" at one place for better and faster understanding.
Step 5
In this step, we need to add new action into your controller for the Get Action method. Here, I have added the "Lang" Action into "Home" Controller. Please write this following code:
Code Ref
- public ActionResult Lang()
- {
- return View();
- }
Step 6
In this step, we need to add a view for the Action & design. Right-click on Action Method (here right-click on form action) > Add View... > Enter View Name >
Code Ref
- @*inherit model calss file to access all input fields and its validation message.*@
- @model MultilingualMVCApp.Models.SignUp
-
- @{
-
- ViewBag.Title = MultilingualMVCApp.Resource.Register;
- }
-
- <h2>@MultilingualMVCApp.Resource.Register</h2>
-
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- @*All input fields validation messages are mentioned.*@
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="@MultilingualMVCApp.Resource.Submit" class="btn btn-default" />
- <input type="reset" value="@MultilingualMVCApp.Resource.Reset" class="btn btn-reset" />
- </div>
- </div>
- </div>
- }
-
- @*<div>
- @Html.ActionLink("Back to List", "Index")
- </div>*@
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
Code Description
Here I added code with a description in a green comment mark "//" and "@* *@" at one place for better and faster understanding.
Step 7
Here, we need to add another action to your controller for the POST Method. Here, I have added "Lang" Action into "HomeController" Controller for POST Action. Please write the following code:
Code Ref
- [HttpPost]
- public ActionResult Lang(SignUp r)
- {
- return View(r);
- }
Step 8
In this step, we need to add another action to your controller for Change Language. Here, I have added "ChangeLanguage" Action into "HomeController" Controller for changing the language. Please write the following code:
Code Ref
- public ActionResult ChangeLanguage(string lang)
- {
- new LangTrans().SetLanguage(lang);
- return RedirectToAction("Lang", "Home");
- }
Step 9
Here, we need to modify the layout page for showing available languages.
Code Ref
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- <div class="navbar-collapse collapse"> @*This one added for collapse of all languages based on screen resolution.*@
- <ul class="nav navbar-nav">
- @* Here i added for selection of available Languages *@
- @{
- foreach (var i in MultilingualMVCApp.LangTrans.AvailableLanguages)
- {
- <li style="color:white; font-size:large">@Html.ActionLink(i.LangFullName, "ChangeLanguage", "Home", new { lang = i.LangCultureName }, null) <text> </text></li>
- }
- }
- </ul>
- </div>
-
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- </div>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts", required: false)
- </body>
- </html>
Code Description
Here, I added code with a description in a green comment mark "//" and "@* *@" at one place for better and faster understanding.
Step 10
Here, we set as start page in MVC in the RouteConfig.cs file.
Code Ref
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Lang", id = UrlParameter.Optional }
- );
Output
The content is translated into English.
The content is translated into Spanish.
The content is translated into the Bengali language.
The content is translated into the Oriya language.
The validation message content is translated into the English language.
The validation message content is translated into the Oriya language.
Link To Source Code:
In this article, we have learned:
- Introduction to multilingual Asp.net MVC Application
- Configure resource files in MVC Application
- Way to set-up ISO Language code for translating content
- Manage Languages property and function using C#