I am using asp.net mvc. I have 4 pages that show list of events(different type of events) and \"Details\" link on each page leads to \"EventDescription.aspx\" View.
The
I suggest you use TempData instead of ViewData. For instance you could have a setting like this.
public ActionResult Details(int id)
{
var event = repository.GetByID(id);
if (event != null)
{
TempData["ReturnPath"] = Request.UrlReferrer.ToString();
return View(event);
}
else { //....... ; }
}
And in your View you could have a regular ActionLink like so
<% =Html.ActionLink("Back To Events", TempData["ReturnPath"]) %>
If you want to be DRY, you could also create an Action method in your controller just to handle the redirects like so.
public ActionResult GoBack()
{
return Redirect(TempData["ReturnPath"]);
}
And in your View a normal ActionLink like so
<% =Html.ActionLink("Back To Events", "GoBack") %>
When you render the page, you also need to render a link that will point to the correct page when Back to Events is clicked. This is best set up in the controller method, where you readily have access to all of the necessary information.
An easy way to do this is to put the return link information in a ViewData variable
(untested pseudocode follows). In your controller method:
ViewData["ReturnPath"] = "/Content/Page/1";
And then in your view:
<% =Html.ActionLink("Back To Events", ViewData["ReturnPath"]) %>
or something similar.
Alternatively, you could try something like
ViewContext.RouteData.Values["action"]
...if you don't mind the magic string there. This will give you the calling action.
if you just want to get the Url where you came from you can do this in your Action
ViewData["ReturnPath"] = this.Request.UrlReferrer.AbsolutePath;
This give you the Url of the page where you came from. If your from Page1 then you go to EventDescription. In your EventDescription Action, your ReturnPath ViewData has the Url of Page1. Or Vice Versa.
Put the return path in TempData (not ViewData) and it can pass from the calling page to the Details page. See also http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/