Maintain Scroll Position On Page Refresh Using ASP.NET or jQuery

14. September 2009

There is a feature of ASP.NET that isn't widely known called MaintainScrollPositionOnPostback, which is a common way of maintaining the scroll position after a Postback. Behind the scenes ASP.NET passes a hidden variable with the page location and resets it with JavaScript after the page re-renders.

<%@ Page 
   Title="Page Title Here" 
   MaintainScrollPositionOnPostback="true" 
   Language="C#" 
   MasterPageFile="~/YourMasterPage.master" 
   AutoEventWireup="true" 
   CodeBehind="YourCodeBehind.aspx.cs" 
   Inherits="YourCodeBehind" %>

However, this method will not work if the Postback does a Redirect on the server.

If the Postback does a Redirect instead of re-rendering the same page, then you could use the ScrollSaver jQuery script. All you have to do is include the script on the page and before a Postback occurs it will save the location of each element in a cookie and then restore it when the page re-renders. This will work for both a Postback and a Redirect.

All you have to do is include the jQuery plugin into your page. You don’t have to actually call any jQuery methods… it just does everything for you!

<script type="text/javascript" src="scrollsaver.min.js"></script>

I would recommend only adding this script to the page you are interested in maintaining position in order to minimize any risk of affecting other pages in your project. The overhead of the minimized plugin is only 1.63K and when you consider it will get cached on the client that is pretty good :)

Blog ,


Comments

9/14/2009 8:58:41 PM #
Elijah,

Thanks for a wonderful tip. I'll be using it for my district work for an AJAX enabled MVC web app which I am building. That will be fantastic for doing multiple entries per sitting.
9/14/2009 9:27:43 PM #
Maintain Scroll Position On Page Refresh Using ASP.NET or jQuery

You've been kicked (a good thing) - Trackback from DotNetKicks.com
Stephen
Stephen
9/15/2009 3:53:52 AM #
Great find!! Thank you for sharing.
Folsco.Net
Folsco.Net
9/15/2009 3:30:26 PM #
As an addendum, MaintainScrollPositionOnPostback can also be set for all pages in your application, yes, all at once.  Do this in the configuration file (web.config), as follows:

<system.web>
   <pages maintainScrollPositionOnPostback="true" ... />
</system.web>

.Net Rocks.
J.R.
J.R.
10/13/2009 1:40:04 AM #
Outstanding!  Thank you!  This is the simplest and best solution I have seen to this issue.  

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading