I am trying to develop a MVC3 (razor) application with Select language functionality.
Using the following view as a Partial view on _Layout.cshtml
_SelectCulture
<text>
@Html.ActionLink("English", "SetCulture", new { controller = "Culture", culture = "en-GB" })
|
@Html.ActionLink("Welsh", "SetCulture", new { controller = "Culture", culture = "cy-GB" })
</text>
<div>
@System.Threading.Thread.CurrentThread.CurrentUICulture.ToString()
</div>
CultureController
public ActionResult SetCulture(string culture)
{
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
return RedirectToAction("Index", "Home");
}
But its Still not changing the Language.
Any help please.
Thanks
Well, you are changing the language of the current thread. The current thread ends with the current request which is a little bit later after your controller action executes. Then you are redirecting to some other controller action. Then ASP.NET spawns a new thread to serve this request which obviously doesn’t have the culture set.
So you will have to persist this change somewhere. Basically there are 3 different approaches:
I am putting them in the order of preference. The first approach consists into integrating a
{culture}token in all your routes. IMHO this is the best approach in terms of SEO as well. So you will redirect for example to/fr/home/indexif you want to get your site in French. You could then use a custom action filter attribute which will run before each action, inspect the culture route parameter and set the current thread culture (this time for the current action).Cookies and sessions also involve persisting the current language between the requests. In the first example this is done on the client whereas in the second it is done in the server. Once again a custom action filter could be used to read the value of the language before each action and reflect the current thread culture.
You may take a look at the following guide which uses Session to persist the current language.