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:
Website\page3
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?
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¶mB=bar&returnUrl=" + HttpUtility.UrlEncode(page0.ToString()));
Console.WriteLine("Page 1: {0}", page1);
var page2 = new Uri("http://www.example.com/page2?paramC=baz¶mD=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¶mB=bar&returnUrl=http:%2f%2fwww.example.com%2fpage0
Page 2: http://www.example.com/page2?paramC=baz¶mD=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¶mB=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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With