Thursday, June 16, 2011

How To Maintain Page Scroll On Postback in ASP.NET

There is nothing more annoying to your visitors than making a selection from a drop down list, then being surprised when the page jumps back to the top when it refreshes. This leaves them disoriented and disrupts the flow of concentration while they fill out your silly form.

In order to maintain you pages scroll position on PostBack, ASP.NET gives us 3 methods to use from to achieve the same goal.

1.   Web.Config - In the applications web.config file, we can add the maintainScrollPositionOnPostBack attribute to the Pages tag and set it to true. This method will affect all of the pages within the website.
Example: <pages maintainScrollPositionOnPostBack="true" />

2.   Page Directive -  We can use the same attribute used in method one to affect only this single page by adding the directive to its Page directive.
Example: <%@ Page MaintainScrollPositionOnPostback="true" />

3.   Code Behind -  In the code behind page we can programmatically control the scroll position of the page. As with method 2, this method will affect only this single page.
Example (C#): System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;

One final note: If you are using ASP.NET's built in form validation controls you're probably pulling your hair out wondering why this doesn't work. None of the above methods will work without making use of a little javascript workaround. I will not go into details but if you need them just google the pfrase "MaintainScrollPositionOnPostback and form validation".

Here is the fix. Place it between you pages <head> tags:

<script type="text/javascript">
       window.scrollTo = function () { }
</script>

No comments: