ASP.NET

Maintain Scroll Position on Postback in ASP.NET 2.0

When working with a lengthy web page that spans many vertical “pages,” scrolling down and then doing something that causes a postback results with the posted back page sitting back up at the top rather than auto-scrolling down to the location where the postback was triggered. With ASP.NET 1.x, this problem can be easily overcome with a bit of JavaScript and server-side code. See Maintaining Scroll Position on Postback for more information.

ASP.NET 2.0 makes maintaining scroll position on postback much easier, although it's not a well-document or oft-discussed feature. When I show this little tip at User Group talks, to clients, or to my class, I'd say more than 90% of the people didn't know about this, are impressed, and wonder aloud, “Why isn't this common knowledge?”

Anyway, to have a single page remember scroll position on postback, simply set the MaintainScrollPositionOnPostback attribute in the @Page directive to True. That's it! The page will then automagically inject the needed JavaScript and server-side logic to make this feature a reality.

<%@ Page Language="..." MaintainScrollPositionOnPostback="true" ... %>

Alternatively, you can enable this feature for all pages in the site by setting it in the <pages> element in Web.config.

<pages maintainScrollPositionOnPostBack="true" />

11/27/2007 4:08:51 AM Category ASP.NET

People who read this, also read...


Back