Tuesday, February 24, 2009

Scroll to top on partial postback

In one of a project that I worked on we had a datalist with paging(datapager). The datalist was in an update panel to give the ajax impact and to improve the performance. The issue was when you scroll down to the page and move to the next page the page doesnt scroll up after partial postback.

It can be done by adding the following code in code-behind file in page load for example.

if (System.Web.UI.ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)
System.Web.UI.ScriptManager.RegisterStartupScript(this, typeof(MyPage), "pagingAnchor", "window.location.href = '#';", true);

Where MyPage is the name of your page or control.

This javascript code needs to be added in the page to cancel the default scroll behavior.

var prm = Sys.WebForms.PageRequestManager.getInstance();
function beginRequest()
prm._scrollPosition = null;