在MVC5中,我希望我的SetCulture操作具有行为,这样在完成后,它会返回到调用它的原始操作 - 包括参数。
对于没有参数的动作来说,这似乎很容易。视图中的Html.ActionLink
:
@Html.ActionLink("中文 (臺灣)", "SetCulture", "Home", routeValues: new { culture = "zh-tw", currentController = ViewContext.RouteData.Values["controller"], currentAction = ViewContext.RouteData.Values["action"] }, htmlAttributes: new { id = "zh-tw" })
然后是控制器:
public ActionResult SetCulture(string culture, string currentController, string currentAction)
{
// Validate input
culture = CultureHelper.GetImplementedCulture(culture);
// Save culture in a cookie
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = culture; // update cookie value
else
{
cookie = new HttpCookie("_culture");
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
return RedirectToAction(currentAction, currentController);
}
这很好用。但是,当它被调用的动作是,例如:public ActionResult ClassTimeTable(DateTime date)
现在,我知道将SetCulture放回主页很容易。但是如果可以的话,我想解决这个问题。
答案 0 :(得分:1)
只需将URL作为参数传递,然后重定向回该网址:
@Html.ActionLink("中文 (臺灣)", "SetCulture", "Home", routeValues: new { culture = "zh-tw", url = Request.Url.ToString() }, htmlAttributes: new { id = "zh-tw" })
然后你的方法是:
public ActionResult SetCulture(string culture, string url)
{
// Validate input
culture = CultureHelper.GetImplementedCulture(culture);
// Save culture in a cookie
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = culture; // update cookie value
else
{
cookie = new HttpCookie("_culture");
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
return Redirect(url);
}