What is the best way to reset the scroll position to the top of page after the an asynchronous postback?
The asynchronous postback is initiated from a ASP.NET GridView CommandField column and the ASP.NET update panel Update method is called in the GridView OnRowCommand.
My current application is an ASP.NET 3.5 web site.
EDIT: I have received excellent feedback from everyone, and I ended using the PageRequestManager method in a script tag, but my next question is:
How do I configure it to only execute when the user clicks the ASP.NET CommandField in my GridView control? I have other buttons on the page that perform an asynchronous postback that I do not want to scroll to the top of the page.
EDIT 1: I have developed a solution where I do not need to use the PageRequestManager. See my follow up answer for solution.
Here is the following solution I developed based on this source
ASP.NET Webform
<script language="javascript" type="text/javascript">
function SetScrollEvent() {
window.scrollTo(0,0);
}
</script>
<asp:GridView id="MyGridView" runat="server" OnRowDataBound="MyGridView_OnRowDataBound">
<Columns>
<asp:CommandField ButtonType="Link" ShowEditButton="true" />
</Columns>
</asp:GridView>
ASP.NET Webform code behind
protected void MyGridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType.Equals(DataControlRowType.DataRow))
{
foreach (DataControlFieldCell cell in e.Row.Cells)
{
foreach(Control control in cell.Controls)
{
LinkButton lb = control as LinkButton;
if (lb != null && lb.CommandName == "Edit")
lb.Attributes.Add("onclick", "SetScrollEvent();");
}
}
}
}