.Net Resetting Scroll Position When MaintainScrollPositionOnPostBack = True

10. December 2009

Read this article in your language IT | EN | DE | ES

Had a friend have an issue where he had select buttons on a gridview and on selected changed event he would update control at the top of his page.  However, he had MaintainScrollPositionOnPostBack set to True, so of course the browser would reload and scroll down to where he had clicked the Select button.

Found this article how to override the MaintainScrollPosition so it would go to the top of the page.  Works like a charm.

http://www.4guysfromrolla.com/articles/111407-1.aspx

On postback, the ASP.NET page adds a call to the client-side function WebForm_RestoreScrollPosition(), which returns the browser's scroll position to the X and Y coordinates specified by the __SCROLLPOSITIONX and __SCROLLPOSITIONY form fields (which were assigned the browser's scroll position before the postback ensued). Consequently, the browser's scroll position is maintained across postbacks. The diagram below illustrates this interaction graphically.

In order to reset the scroll position, we need to add the above JavaScript to the rendered page's output and then call it before the call to WebForm_RestoreScrollPosition(). The following code adds a function (ResetScrollPosition) to the outputted markup and then injects a line of script that invokes this function. The server-side code uses the RegisterClientScriptBlock method to register the ResetScrollPosition function, which adds the function to the top of the form. As noted earlier, RegisterStartupScript adds a call to ResetScrollPosition at the bottom of the page.

Private Sub ResetScrollPosition()
If Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "CreateResetScrollPosition") Then
'Create the ResetScrollPosition() function
ClientScript.RegisterClientScriptBlock(Me.GetType(), "CreateResetScrollPosition", _
"function ResetScrollPosition() {" & vbCrLf & _
" var scrollX = document.getElementById('__SCROLLPOSITIONX');" & vbCrLf & _
" var scrollY = document.getElementById('__SCROLLPOSITIONY');" & vbCrLf & _
" if (scrollX && scrollY) {" & vbCrLf & _
" scrollX.value = 0;" & vbCrLf & _
" scrollY.value = 0;" & vbCrLf & _
" }" & vbCrLf & _
"}", True)
'Add the call to the ResetScrollPosition() function
ClientScript.RegisterStartupScript(Me.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", True)
End If
End Sub

To reset scroll position on postback, simply call the server-side ResetScrollPosition() method from the appropriate event handler (be it the Click event handler of a Button, the PageIndexChanged event of the GridView, or some other event).

Rest of Article

ASP.NET, Programming, Code Snippets , , ,