ViVi ViVi - 6 days ago 6
ASP.NET (C#) Question

Using multiple languages in asp.net mvc website

I am trying to provide user an option to change the UI language of my asp.net mvc website. I am planning to offer 2 languages to the user ie : English and Dutch

For that I edited my web.config file and added :

<globalization enableClientBasedCulture="true" culture="auto" uiCulture="auto"/>


Now I added 2 files
Resources.resx
(the default file) and
Resources.nl-NL.resx
(the resource file for dutch).

I am referring to the Resources file from my view as
<title>@WebApplication9.App_GlobalResources.Resources.RequestTitle</title>
.

When the language is changed, I am changing the Culture like this :

Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-NL");


But even after the language change to dutch and changing the culture values to the ones specified above, the English value from
Resources.resx
is always show instead of getting the value from
Resources.nl-NL.resx
.

Could you please help me to find out what I am missing here?

Answer

I have resolved the issue by setting the culture for the current each time while a controller action method is called. The issue is caused since when I change the culture, it is set for current thread only. When user requests for another view, the thread might be different. So I need to set the Culture for each new request/new thread.

I give the user to have only 2 languages ie English(en-US) and Dutch(nl-NL). So I created 2 resx files with names Resources.resx for English and Resources.nl.resx for Dutch. When user changes the current language I keep the language in Session and stores in database for remembering it during further logins.

if(selectedLang == Dutch)
{
    Session["Language"] = "nl-NL";
}
else
{
    Session["Language"] = "en-US";
}

Now the Session["Language"] holds the user's preferred language. Now in each controller action method :

[HttpGet]
public ActionResult ActionMethodName(DataClass dataObj)
{
    Sessions.ChangeLanguage(Session["Language"].ToString());
}

Sessions.ChangeLanguage(string language) is a static method in a class Sessions as below :

public static void ChangeLanguage(string lang)
{
    Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
}
Comments