Keep Your Scroll Position After Postbacks

Posting back to the server can rob your browser of its scroll position, but it doesn't have to.

Jeff Prosise

October 30, 2009

2 Min Read
ITPro Today logo in a gray background | ITPro Today

Hot Tip

LANGUAGES:C# | JavaScript

TECHNOLOGIES:Postbacks | HTML

 

Keep Your Scroll Position After Postbacks

Posting back to the server can rob your browser of itsscroll position, but it doesn't have to.

 

By Jeff Prosise

 

ASP.NET programmers often bemoan the fact that postingback to the server makes the browser lose its scroll position, causing the pageto scroll back to the top. Here's a solution that relies on client-sideJavaScript to transmit the current scroll position - along with the form's otherpostback data. It then writes out a tag containing an onloadattribute, which restores the scroll position following a postback. In otherwords, it prevents the page from scrolling back to the after clicking on asubmit button. Try this code:

 

<%@ Page Language="C#" %>

 

  <%

    if(Request["__SCROLLPOS"] != null &&

     Request["__SCROLLPOS"] != String.Empty) {

       int pos =Convert.ToInt32 (Request["__SCROLLPOS"]);

       Response.Write("        "onload="javascript:myBody.scrollTop=" +        pos +";">");     }    else       Response.Write("");   %>          "javascript:return onSubmitForm ();"runat="server">                                   

 

function onSubmitForm (){    myForm.__SCROLLPOS.value = myBody.scrollTop;     return true; }

 

To see for yourself, add enough content to the page tocause a scrollbar to appear. Then scroll to the bottom of the page and click onthe Test button; the scroll position will be preserved.

 

This technique's chief limitation is it works only whenthe postback is generated by a Button control. Other controls that forcepostbacks - controls such as LinkButton and Calendar - generate postbacksprogrammatically, which prevents the onSubmitForm function from being called.Still, this technique is very useful for forms containing conventional pushbuttons.

 

Jeff Prosise isauthor of several books, including ProgrammingMicrosoft .NET (Microsoft Press). He also is a co-founder of Wintellect(http://www.wintellect.com), asoftware consulting and education firm that specializes in .NET.

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like