0

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

So something like, @Html.ActionLink("More Info", "InfoPage", new { returnUrl = Request.Url }) ??
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.