ASP.NET MVC5通过单击HTML

时间:2016-12-14 10:55:55

标签: c# asp.net-mvc-5 multilingual

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");
    }
}

然后在你看来:

<a href="@Url.Action("SetLanguage", "Language", new { @name = "pl" })">Polski</a>
<a href="@Url.Action("SetLanguage", "Language", new { @name = "en" })">English</a>

我正在使用上面的代码在我的视图中设置语言,但如果我们点击每个按钮语言会相应更改,则会有两个按钮。但我需要用一个按钮来实现这一点,如果用户选择语言为英语按钮必须更改为法语,如果用户选择语言为法语,则按钮必须更改为英语。页面必须采取相应的行动。

如何使用一个按钮实现这一目标?

1 个答案:

答案 0 :(得分:2)

如果您只使用2种语言, 只需按下一个按钮,每次点击都会翻转语言并处理来自ViewBag或Javascript的按钮文本,如下所示:

    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");
        }
    }