Hanshan
Hanshan

Reputation: 3764

MVC5 Retrieve RouteValues Of Parameters For Current Request

In MVC5 I want to have behavior for my SetCulture action such that, after it completes, it returns to the original action from which it was called - including parameters.

It seems easy enough for me to do this for actions without parameters. An Html.ActionLink in the view:

@Html.ActionLink("中文 (臺灣)", "SetCulture", "Home", routeValues: new { culture = "zh-tw", currentController = ViewContext.RouteData.Values["controller"], currentAction = ViewContext.RouteData.Values["action"] }, htmlAttributes: new { id = "zh-tw" })

And then the controller:

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

This works nicely. But, I'm stumped when the action from which it is called is, e.g.: public ActionResult ClassTimeTable(DateTime date)

Now, I know it would be easy to just throw the SetCulture back to the home page. But I would like to solve this problem if I can.

Upvotes: 1

Views: 550

Answers (1)

Mathew Thompson
Mathew Thompson

Reputation: 56449

Just pass the URL in as a parameter, then redirect back to that URL:

@Html.ActionLink("中文 (臺灣)", "SetCulture", "Home", routeValues: new { culture = "zh-tw", url = Request.Url.ToString() }, htmlAttributes: new { id = "zh-tw" })

Then your method would be:

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

Upvotes: 1

Related Questions