Tuesday, September 26, 2006

Asp.net retain Scroll Position after postback

When any control in an ASP.NET WebForm does a postback to the server, the page scrolls to the top after the postback is completed. Users will find the process of scrolling down to the place where they posted the form cumbersome.

This article explains how to retain a page's scroll position after a postback to the server.

ASP.NET automaticaly creates two HTML hidden fields when a server side form contains controls that performs postback to the server. These fields are given below (they can be seen by viewing the source code of the page):

<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />

The __doPostBack() client side JavaScript function is automatically generated by ASP.NET to handle the postback event. The value for these hidden fields will be set in the client script handler as shown below:

<script language="javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform = document.ctrl0;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>

The value of the __EVENTTARGET field will be set to the name of the control which does the postback. This value can be accessed from the server-side by using Request.Form ["__EVENTTARGET"].

To enable the page to retain its scroll position, a HTML anchor is created just above the control that does the postback. The name of the anchor should be the same as that of the control.

<a name="#DROPDOWN1"></a>
<ASP:DropDownList id=DropDown1 runat="server" AutoPostBack="True">
<ASP:Listitem Text="Horizontal"/>
<ASP:Listitem Text="Vertical"/>
</ASP:DropDownList/>


A client-side JavaScript, coded at the end of the page, is executed after the page loads. This causes the page to scroll to the anchor from where the postback occurred.

<script runat="server">
location.href="#<%=Request.Form["__EVENTTARGET"]%>";
</script>
Get more information
Tags: asp.net, javascript, scroll position, postback, retain scroll, dopostback
Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Comments on "Asp.net retain Scroll Position after postback"