2015-06-11 48 views
1

在MVC5中,我希望對我的SetCulture操作有這樣的行爲,以便在它完成後,它返回到調用它的原始操作 - 包括參數。MVC5檢索當前請求的參數RouteValues

對於沒有參數的操作,我似乎很容易做到這一點。在視圖中的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放回主頁會很容易。但是如果可以的話,我想解決這個問題。

回答

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); 
} 
+0

這是輝煌的,非常感謝您的幫助:)很棒。 – Hanshan