I have an ASP.NET MVC app. This app allows the user to set the culture to view the contents of the app in. To do this, the user visits ~/user/language
. They choose the language and click a "Save" button. In my controller, I have the following:
CultureInfo ci = new CultureInfo(model.Culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
return View(model);
When the view is re-loaded, the strings have been translated like I would expect. However, if I visit another page in the app, the strings are NOT translated like I would expect. It's like the culture information isn't being preserved or the thread is being killed.
What am I doing wrong?
@heymega is correct. The current culture is non-persistent. You have to load at the beginning of each request. You need to set the culture to a persistent location (such as a cookie) and then set the culture to the thread in the Application_BeginRequest
event.
A better way than using a cookie is to build the culture into the URL.
http://www.somesite.com/es-MX/somewhere
http://www.somesite.com/en-US/somewhere
This is what search engines expect, it means the user can switch culture easily by switching URLs, and you don't have to keep track of culture on a per user basis. However, you do still need to set the culture at the beginning of each request based on the URL.