How do I redirect to the previous action in ASP.NET MVC?

adolfojp picture adolfojp · May 2, 2009 · Viewed 155.8k times · Source

Lets suppose that I have some pages

  • some.web/articles/details/5
  • some.web/users/info/bob
  • some.web/foo/bar/7

that can call a common utility controller like

locale/change/es or authorization/login

How do I get these methods (change, login) to redirect to the previous actions (details, info, bar) while passing the previous parameters to them (5, bob, 7)?

In short: How do I redirect to the page that I just visited after performing an action in another controller?

Answer

Nathan Ridley picture Nathan Ridley · May 2, 2009

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}