In this article I am going to explain how to handle multiple language in your ASP.NET MVC web site.
This a very basic step.
Step 1
Create ASP.NET MVC web application
Step 2
Add new controller called BaseController. (any name as you wish)
override BeginExecuteCore() method.
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string language = "en";
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
language = cultureCookie.Value;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(language);
return base.BeginExecuteCore(callback, state);
}
Step 3
Inherit Home Controller from BaseController
public class HomeController : BaseController
step 4
Add action to change language.
To store the culture I have used cookies. It is a simple way.
public ActionResult ChangeLanguage(string lang) {
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = lang;
else
{
cookie = new HttpCookie("_culture");
cookie.Value = lang;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
return RedirectToAction("Index");
}
step 5
Add resource files.
Different languages are stored in resource files.
For this demo I have used English, Dutch and french languages.
I have added three resource files naming as follow
Resource.resx -> default resource file for English language
Resource.fr.resx -> French language
Resource.nl.resx -> Dutch
Add each language words for the English word “Wel Come”
add words as above and build the project.
step 6
add view to change language. Wellcome text will be changes according to language selections.
It is used in view as @Resources.Resource.wellcome .
Behind the seen it is checked current culture and set appropriate word using resource files.
step 7
Done. Run the project and click links to change language