Reputation: 5670
I want to have a View that has a link that will be set to the url of whatever page the user navigated to this view from.
Let's say I have a View and relative Action named InfoPage, and on this page I want a link that simply says 'Return'.
If the user is on PageA and navigates to InfoPage, clicking the 'Return' link returns the user to PageA.
If the user is on PageB and navigates to InfoPage, clicking the 'Return' link returns the user to PageB.
I'm thinking the easiest means to do this will be to add the 'ReturnUrl' as a property of the model used in InfoPage.
My question this is how do I get that return url.
public ViewResult InfoPage(){
var model = new InfoPageModel();
//Set my model's other properties here...
model.ReturnUrl = ''//Where do I get this?
return view(model);
}
And then in my view
<a href="@Model.ReturnUrl">Return</a>
Upvotes: 0
Views: 2008
Reputation: 1316
To dynamically construct a returnUrl within any controller action:
var formCollection =
new FormCollection
{
new FormCollection(this.HttpContext.Request.Form),
new FormCollection(this.HttpContext.Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
var returnUrl =
this.Url.Action(
this.RouteData.Values["action"].ToString(),
this.RouteData.Values["controller"].ToString(),
parameters
);
Related: How do I redirect to the previous action in ASP.NET MVC? (Same but from within any View)
Upvotes: 1
Reputation: 887469
The most robust way to do this is to pass a query-string parameter to your page from the caller page. Every link to this page will be required to pass its own URL. (Request.Url
).
You could also use Request.UrlReferrer
in your control, but not all browsers send Referer
headers.
Upvotes: 1