Reputation: 11
public class LanguageController : Controller
{
public ActionResult SetLanguage(string name)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(name);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
HttpContext.Current.Session["culture"] = name;
return RedirectToAction("Index", "Home");
}
}
Then in your view:
<a href="@Url.Action("SetLanguage", "Language", new { @name = "pl" })">Polski</a>
<a href="@Url.Action("SetLanguage", "Language", new { @name = "en" })">English</a>
I am using the above code to set language in my view, but this has two buttons if we click on each button the language changes accordingly. But I need this to happen with one button like if the user selected language as English the button has to change to french and if user selects language as French the button has to change to English. And the page has to act accordingly.
How to achieve this using one button?
Upvotes: 1
Views: 2319
Reputation: 111
In case you are only working with 2 languages, just make one button that flips the language every time clicked and handle the button text from a ViewBag or Javascript like this:
public class LanguageController : Controller
{
public ActionResult ChangeLanguage()
{
if (Thread.CurrentThread.CurrentCulture.Name == "en-US")
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
ViewBag.CultBtn = "En";
}
else
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
ViewBag.CultBtn = "Fr";
}
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
HttpContext.Current.Session["culture"] = Thread.CurrentThread.CurrentCulture.Name;
return RedirectToAction("Index", "Home");
}
}
Upvotes: 3