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

166,920

Solution 1

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

Solution 2

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

Solution 3

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

return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());

Solution 4

A suggestion for how to do this such that:

  1. the return url survives a form's POST request (and any failed validations)
  2. the return url is determined from the initial referral url
  3. without using TempData[] or other server-side state
  4. handles direct navigation to the action (by providing a default redirect)

.

public ActionResult Create(string returnUrl)
{
    // If no return url supplied, use referrer url.
    // Protect against endless loop by checking for empty referrer.
    if (String.IsNullOrEmpty(returnUrl)
        && Request.UrlReferrer != null
        && Request.UrlReferrer.ToString().Length > 0)
    {
        return RedirectToAction("Create",
            new { returnUrl = Request.UrlReferrer.ToString() });
    }

    // Do stuff...
    MyEntity entity = GetNewEntity();

    return View(entity);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
    try
    {
        // TODO: add create logic here

        // If redirect supplied, then do it, otherwise use a default
        if (!String.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index");
    }
    catch
    {
        return View();  // Reshow this view, with errors
    }
}

You could use the redirect within the view like this:

<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
    <a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>

Solution 5

In Mvc using plain html in View Page with java script onclick

<input type="button" value="GO BACK" class="btn btn-primary" 
onclick="location.href='@Request.UrlReferrer'" />

This works great. hope helps someone.

@JuanPieterse has already answered using @Html.ActionLink so if possible someone can comment or answer using @Url.Action

Share:
166,920
adolfojp
Author by

adolfojp

Updated on December 24, 2020

Comments

  • adolfojp
    adolfojp over 3 years

    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?

  • Syd
    Syd about 14 years
    Just a suggestion: you can use "Redirect" explictly is harder to unit test your controller. You are better off using a "RedirectToAction" instead.
  • fulvio
    fulvio about 12 years
    I'd recommend using Request.Url.AbsolutePath.ToString() as the AccountController's LogOn method contains checks for URL's beginning with '/', etc.
  • Rahatur
    Rahatur over 11 years
    @gotnull Request.Url.AbsolutePath will redirect to the same action. Which is not the desired output. We have to return to the second last action. For that we could write: return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.T‌​oString());
  • one.beat.consumer
    one.beat.consumer over 11 years
    @nathanridley: This does not work for POST requests. Say the user is on GET Index then GET Edit. The referring URL then is Index but then when the user does POST Edit the referrer is now Edit from the preceding GET request. How can I make sure POST Edit knows the URL that referred the user to GET Edit?
  • QMaster
    QMaster over 9 years
    UrlReferrer is NULL when I was in the some page and want to get to view I know got error just by entering URL in address bar. Why when I enter URL in Address Bar it can't determine UrlReferrer?
  • Jess
    Jess about 4 years
    Putting the redirect URL on the query string is a smart thing to do. If your authentication scheme does redirects, it will get in the way of this feature.