Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 805
adolfojp Avatar asked Sep 29 '22 01:09

adolfojp


People also ask

How do I redirect to another action?

To redirect the user to another action method from the controller action method, we can use RedirectToAction method. Above action method will simply redirect the user to Create action method.

What is used to redirect from one action to another in MVC core?

RedirectToActionResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header. It targets a controller action, taking in action name, controller name, and route value.


Video Answer


3 Answers

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"]);
}
like image 101
Nathan Ridley Avatar answered Oct 30 '22 01:10

Nathan Ridley


If you want to redirect from a button in the View you could use:

@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})
like image 20
IUnknown Avatar answered Oct 30 '22 01:10

IUnknown


If you are not concerned with unit testing then you can simply write:

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
like image 44
Rahatur Avatar answered Oct 30 '22 02:10

Rahatur