使用下拉列表更改mvc4 razor中的语言

时间:2017-02-03 11:00:58

标签: c# asp.net-mvc-4 razor drop-down-menu resx

我有一个应该是双语的MVC4网络应用程序(剃须刀)。我有一个资源文件夹,其中有2个resx文件,名为 Home.resx Home.de.resx 。我设法制作了两个链接,将语言更改为 en de

<li class="dropdown">
    <ul>
        <li>
            <a href="@Url.Action("ChangeCulture", "Home", new { lang = "en" })">English</a>
        </li>
        <li>
            <a href="@Url.Action("ChangeCulture", "Home", new { lang = "de" })">Deutsch</a>
        </li>
    </ul>
</li>

这是我在 HomeController.cs

中添加的内容
public ActionResult ChangeCulture(string lang)
{
    var langCookie = new HttpCookie("lang", lang) { HttpOnly = true };
    Response.AppendCookie(langCookie);
    return RedirectToAction("Index", "Home", new { culture = lang });
}

以下是 Global.asax.cs

中的代码
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    var handler = Context.Handler as MvcHandler;
    var routeData = handler != null ? handler.RequestContext.RouteData : null;
    var routeCulture = routeData != null ? routeData.Values["culture"].ToString() : null;
    var languageCookie = HttpContext.Current.Request.Cookies["lang"];
    var userLanguages = HttpContext.Current.Request.UserLanguages;

    // Set the Culture based on a route, a cookie or the browser settings,
    // or default value if something went wrong
    var cultureInfo = new CultureInfo(routeCulture ?? (languageCookie != null ? languageCookie.Value
           : userLanguages != null ? userLanguages[0] : "en"));

    Thread.CurrentThread.CurrentUICulture = cultureInfo;
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
}

还修改了 RouteConfig

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{culture}/{controller}/{action}/{id}",
    defaults: new { culture = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

现在,问题是 - 如何使用DropDownList实现这一目标? 我尝试过以下代码,但不会改变语言:

<li id="language">
    <form class="form " id="Form1" method="post" name="forma">
    <input name="formDate" value="123" type="hidden">
        <div class="control-group input-select-wrapper">
            <select class="aui-field-select" id="Select1" name="forma_languageId" onchange="submitForm(document.forma);" title="Language (Changing the value of this field will reload the page.)">
                <option class="taglib-language-option" value="en" lang="en">
                    English
                </option>
                <option class="taglib-language-option" value="de" lang="de">
                    Deutsch
                </option>
            </select>
        </div>
    </form>
</li>

我错过了什么吗?或者这不是正确的方法? 感谢

0 个答案:

没有答案