Reputation: 17186
I have several resource files for each language I want to support, named like below:
NavigationMenu.en-US.resx
NavigationMenu.ru-RU.resx
NavigationMenu.uk-UA.resx
Files are located in MySolution/Resources/NavigationMenu
folder.
I have action which sets CurrentCulture
and CurrentUICulture
like below
public ActionResult SetLanguage(string lang)
{
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
return Redirect(Request.UrlReferrer.AbsoluteUri);
}
catch(Exception)
{
return RedirectToAction("Index");
}
}
lang
parameter values are uk-UA
, ru-RU
or en-US
depending on what link in my view was clicked. Also I have web config globalization defined section:
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="ru-RU" uiCulture="ru-RU" />
When my application starts I have Russian language as expected but when I try to change my language with SetLanguage
action to English I get no language changes in my views. NavigationMenu.SomeProperty
is still Russian. What am I missing?
Upvotes: 5
Views: 36638
Reputation: 7752
Persist your language in e.g cookie in your SetLanguage()
and then in the BaseController
or ActionFilter
(recommended) get the values from cookie and the update the threads accordingly.
if this doesn't make any sense, take a look at the following nice articles;
CodeProject : http://www.codeproject.com/Articles/526827/MVC-Basic-Site-Step-1-Multilingual-Site-Skeleton
And this One :http://afana.me/post/aspnet-mvc-internationalization.aspx
e.g;
// Save culture in a cookie
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = culture; // update cookie value
else
{
cookie = new HttpCookie("_culture");
cookie.HttpOnly = false; // Not accessible by JS.
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
Upvotes: 4
Reputation: 15513
You are updating the culture for the current thread only.
Most sites support localization by including this as part of their URL (in all pages). And with MVC, you can implement this approach by processing the culture using an action filter. This answer has a good solution for this.
Aside from this, you would need to implement this by either persisting the culture to the session or a cookie, and then updating the thread's culture on every request, again by implementing an action filter, or during an application event that contains the request context, such as AquireRequestState.
Upvotes: 6