1
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?

kayess
  • 3,384
  • 9
  • 28
  • 45
Harish
  • 11
  • 2
  • I think your issue implements 2 tasks: first to change page language after button click and then setting button caption to other language had been set previously, but I need to know further what you've tried to solve it (including code if necessary). – Tetsuya Yamamoto Dec 16 '16 at 02:51
  • See [ASP.NET MVC 5 culture in route and url](https://stackoverflow.com/q/32764989) – NightOwl888 Mar 12 '18 at 09:00

1 Answers1

3

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");
        }
    }
Ahmed Mustafa
  • 101
  • 1
  • 9