Jon's Blog

.NET Development & More

ASP.NET AJAX: Return to Top of Page After Partial Postback

After an AJAX partial postback you may need to return to the top of your ASPX page to display an error message, etc.  Here is one way that I have done it.  You can add the JavaScript function below to your ASPX page and then call the method when needed in your code-behind by using the ScriptManager.RegisterClientScriptBlock method.

ASP.NET C# Code-behind:

ScriptManager.RegisterClientScriptBlock(this, Page.GetType(), 
     "ToTheTop", "ToTopOfPage();", true);

 

JavaScript:

<script type="text/javascript">
    function ToTopOfPage(sender, args) {
        setTimeout("window.scrollTo(0, 0)", 0);
    }
</script>

 

You can also just JavaScript to scroll to the top of the page by using the OnClientClick property of your button.  But this will cause this behavior to occur every time the button is clicked and not just when you want it to happen.  For example:

<asp:Button id="bntTest" runat="server"
Text="Test" OnClick="btn_Test"
OnClientClick="javascript:window.scrollTo(0,0);" />