Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track the previous Urls in MVC

I have a main page which has a few filters that I want to keep when I return to this main url. But after loading another pages I want to go back. It could be easily done by getting the @Request.UrlReferrer. However, it only works when returning to the previous page, I need it for the previous 2 pages.

I could do it by using Session["ReturnToMainUrl"] = Request.UrlReferrer but setting it only when getting off the first page.

So If I have 3 levels:

  1. WebSite\page1?Filter=ABC
  2. WebSite\page2
  3. Website\page3

  4. I am on page2 or page3 now and I want to go back to Website\page1?Filter=ABC

When I am on the page 3 I can use Request.UrlReferrer to go back to page 2, but when I go back to page 1 I need to keep the parameters so I am loading from the Session.

How can I do it in a smarter way, not using sessions?

like image 764
Roger Oliveira Avatar asked May 28 '15 04:05

Roger Oliveira


1 Answers

You should recursively build onto a returnUrl query string parameter as you progress from page to page.

For example: https://dotnetfiddle.net/HtoX6b

var page0 = new Uri("http://www.example.com/page0");
Console.WriteLine("Page 0: {0}", page0);

var page1 = new Uri("http://www.example.com/page1?paramA=foo&paramB=bar&returnUrl=" + HttpUtility.UrlEncode(page0.ToString()));
Console.WriteLine("Page 1: {0}", page1);

var page2 = new Uri("http://www.example.com/page2?paramC=baz&paramD=qux&returnUrl=" + HttpUtility.UrlEncode(page1.ToString()));
Console.WriteLine("Page 2: {0}", page2);


var page2ReturnUrl = HttpUtility.ParseQueryString(page2.Query)["returnUrl"];
Console.WriteLine("Return to page 1 from page 2: {0}", page2ReturnUrl);

var page1ReturnUrl = HttpUtility.ParseQueryString(page1.Query)["returnUrl"];
Console.WriteLine("Return to page 0 from page 1 : {0}", page1ReturnUrl);

Page 0: http://www.example.com/page0
Page 1: http://www.example.com/page1?paramA=foo&paramB=bar&returnUrl=http:%2f%2fwww.example.com%2fpage0
Page 2: http://www.example.com/page2?paramC=baz&paramD=qux&returnUrl=http:%2f%2fwww.example.com%2fpage1%3fparamA%3dfoo%26paramB%3dbar%26returnUrl%3dhttp:%252f%252fwww.example.com%252fpage0

Return to page 1 from page 2: http://www.example.com/page1?paramA=foo&paramB=bar&returnUrl=http:%2f%2fwww.example.com%2fpage0
Return to page 0 from page 1 : http://www.example.com/page0

This could go on for many levels deep, yet the process for deriving the previous page's URL is always the same -- simply decode the returnUrl parameter.

like image 197
kspearrin Avatar answered Oct 28 '22 16:10

kspearrin