I have a curiosity related to culture change in MVC. I tried in 2 ways, but apparently I was wrong somewhere.
In my Web.config I have :
Remove the line in your web.config:
<globalization uiCulture="auto" culture="auto" />
Setting these to auto will default the language to the user's language set on the browser. This is overriding your Thread setting.
It's seems I need to override the culture
for my resource strings
and not the thread
. So my final method is this :
public void ChangeCulture(string lang)
{
Resources.Resources.Culture = new CultureInfo(lang);
Response.Redirect(Request.UrlReferrer.ToString());
}
Hope this helps.
UPDATE :
The code above is not good when your application is used by multiple users, because it sets same culture for every user, no matter what browser they are using.
The good way to do it is to make a method which sets a cookie
in your browser :
public void ChangeCulture(string lang)
{
Response.Cookies.Remove("Language");
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];
if (languageCookie == null) languageCookie = new HttpCookie("Language");
languageCookie.Value = lang;
languageCookie.Expires = DateTime.Now.AddDays(10);
Response.SetCookie(languageCookie);
Response.Redirect(Request.UrlReferrer.ToString());
}
After this ( the tricky way ) you need to make every controller to inherit from one BaseController. It is tricky because you need to override Initialize
.
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["Language"];
if (languageCookie != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(languageCookie.Value);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageCookie.Value);
}
else
{
//other code here
}
base.Initialize(requestContext);
}