Reputation: 110
I have an index action that can be filtered and is done so by using a query string. When I choose a record I move to the Details action. From there I can navigate to other actions related to this record which will then lead me back to the Details action. I would like to be able to save the URL from the Index page which will have the query string parameters intact. Obviously I can't do this with a straight Request.UrlReferrer since it won't be correct if the previous action wasn't Index. I have come up with a solution but I was wondering if there was a better way. Thanks!
public ActionResult Details(int? id)
{
var url = Request.UrlReferrer;
// Save URL if coming from the Employees/Index page
if (url != null && url.AbsolutePath == "/Employees")
Session.Add("OfficeURL", url.ToString());
// Model Stuff
return View();
}
Details View
@Html.ActionLink("Back to List", "Index", null, new { @href = Session["OfficeURL"] })
Upvotes: 0
Views: 242
Reputation: 239210
You need to pass a "return URL" with your links to the other views. Essentially:
Index.cshtml
@Html.ActionLink("View Details", "Details", "Foo", new { returnUrl = Request.RawUrl })
This will have the effect of putting the current index URL in the query string of the link. Then, in your other actions, you'll accept this as a param and store it in ViewBag
:
public ActionResult Details(int? id, string returnUrl = null)
{
...
ViewBag.ReturnUrl = returnUrl;
return View();
}
Then, in these other views, you'll utilize this ViewBag
member in the same way as above:
Details.cshtml
@Html.ActionLink("Click Me!", "Foo", "Foo", new { returnUrl = ViewBag.ReturnUrl })
When you're ready to go back to the index, then, you'd link/redirect to this return URL that you've been passing around.
Upvotes: 1