views:

2301

answers:

3

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?

+3  A: 

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}
Darin Dimitrov
+3  A: 

try:

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

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"]);
}
Nathan Ridley
Close. I used return Redirect(Request.UrlReferrer.ToString());
adolfojp
Just a suggestion: you can use "Redirect" explictly is harder to unit test your controller. You are better off using a "RedirectToAction" instead.
Syd
+3  A: 

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