Search code examples
asp.netdynamic-data

Returning to last viewed List page after insert/edit with ASP.NET Dynamic Data


With a pretty standard Dynamic Data site, when the user edits or inserts a new item and saves, the page does a Response.Redirect(table.ListActionPath), which takes the user back to page 1 of the table.

If they were editing an item on page 10 (or whatever) and want to edit the next item on that page, they have to remember the page number and navigate back to it.

What's the best way to return the user to the list page they last viewed?

I can conceive of some solutions using cookies, session state, or query string values to retain this state and making my own Page Template to incorporate it, but I can't help thinking this must be something that was considered when Dynamic Data was created, and there must be something simpler or built-in to the framework that I'm missing here.


Solution

  • This is what worked for me;

    In ~/DynamicData/PageTemplates/List.aspx wire-up a handler for the onpageindexchanged event:

    <asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource"
    AllowPaging="True" AllowSorting="True" CssClass="gridview" 
    onpageindexchanged="GridView1_PageIndexChanged">
    

    Then in the hander code, save the page index to the session:

    protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    {
        Session.Add("PrevPageIndex", GridView1.PageIndex);
    }
    

    Finally, on page load, if the request is not postback, and is not asyc postback, and if the referrer url is edit.aspx, and if there is a page index in the session, set the page index of the gridview:

    if (!IsPostBack && !IsAsync)
        {
            if (Request.UrlReferrer != null)
            {                
                if (Request.UrlReferrer.ToString().Contains("Edit.aspx"))
                {
                    if (Session["PrevPageIndex"] != null)
                    {
                        GridView1.PageIndex = (int)Session["PrevPageIndex"];
                    }
                }
            }
        }