Search code examples
c#asp.netdatapager

Remember pagination when returning to page with ListView/DataPager


I have a simple ListView paged by a DataPager giving a list of products. When we click on the product we open the product details page. On the details page we want to "return to product list" but of course we want it to remember what page the datapager was at.

Surely this was conceived as a natural design requirement - what is the simple out-of-the-box way to do this?

If we use the QueryStringField property of DataPager we get the page number in the URL so I hoped I could use the referrer URL in the back link, but I have found the Request.UrlReferrer to be unreliable (when I use F5 to debug the app in Internet Explorer for example, Request.UrlReferrer is always null).

I have found some success with storing the page number in a session variable:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["PagerIndex"] != null)
            {
                DataPager1.SetPageProperties((int)Session["PagerIndex"],
                  DataPager1.MaximumRows, false);
            }
        }
    }

    protected void DataPager1_PreRender(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            Session["PagerIndex"] = DataPager1.StartRowIndex;
        }
    }

This method has some drawbacks:

  1. Only works if QueryStringField is blank (so IsPostBack can be detected)
  2. Session/cookie variable required for each pager
  3. Question of how to reset the session/cookie variables arises

What is the "proper" way to do this?

Thanks


Solution

  • If you don't have any filters you can simply recalculate the page on which the product was.

    Another option will be to encode the page (together with possible filter values for the list) in the URL of the product detail page and use them to generate an URL for the list that will be essentially the same as the one of the original list. Even something like the ReturnUrl approach used for login. Sharepoint does similar thing with its lists but I feel the URL can get too messy (and I am not a person that falls for the whole "clean URL" bullshit when I say it is messy it really is)

    One more option would be to pass the product ID to the list page via the URL. The list page can then calculate the appropriate page. This will remove the noise from the URLs