views:

90

answers:

2

Is there an equivalent to Ruby On Rails' redirect_to :back in ASP.NET MVC?

What about after submitting a form? For example:

From page1 user clicks a link to page2. Submits a form on page2, then I want to redirect to page1.

This works great if I hard code the redirect to go to Page1. However if the user clicks a link to page2 from page8, after submitting the form on page2, how can I redirect back to page 8 instead of page1?

A: 

You can get a reference to the previouspage from code, with Page.PreviousPage; though I'm not sure whether this exists in MVC.

You can also just redirect to the referrer:

Response.Redirect(Request.UrlReferrer.ToString());
Jan Jongboom
This works, but what if you are posting back from a form? I'll have to look into how Rails handles this.
mxmissile
+5  A: 

If you want to use Jan's code as the return value of your action then just drop the Response. part as Response.Redirect will return void. You could do this instead...

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

If you are posting back to a form then take a look at this SO question, it might help.

http://stackoverflow.com/questions/1936/how-to-redirecttoaction-in-asp-net-mvc-without-losing-request-data

Paul