tags:

views:

68

answers:

2

I have a ActionLink, that calls my public ActionResult, and I would like it to return back to the page that it was called from, but how?

A: 

Keep in mind that due to the state-less nature of the web, your ActionResult isn't "called from" your ActionLink as much it is simply a url that the user-agent requested.

Because of this, the only real "built-in" way you can know where that user was coming from is by inspecting the http Request headers to see what the referring page was:

string referrer = Request.Headers["referer"];

You'd then be responsible for parsing out the Action method from this url, if you were going to call it directly. Be aware that this referrer may not be a link within your own site.

Kurt Schindler
+1  A: 

There are a couple of tricks that you can use for this.

The simplest is ...

return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);

AbsoluteUri may not give you the exact path you are looking for, but UrlReferrer should have the imformation you are looking for. Redirect returns a subclass of ActionResult so it is a valid return value.

Another idea is to base the redirect location off of stored values. This is useful when you are going to make multiple requests before you want to redirect, such as when you validate a form and show validation issues on the first response. Another situation will be when the referrer is not a local site. In either case, your referrer won't be what you want it to and you will need to retrieve the correct location from somewhere else.

Specific implementations include using a hidden input field on your form, session state, pulling a descriminator value from your route data, or even just a more constant value like HttpContext.Request.ApplicationPath.

Good luck.

Chuck