The problem with the default behaviour of the WebGrid is that when you have AJAX paging and sorting enabled, the user is taken to the top of the page when they click a paging or sorting link. That's because the sorting and paging links are generated with an href value of #, which effectively means "this page", and invariably takes the user to the top of the page because there is no fragment identifier after the # sign. While not wanting to get into a debate about the merits of using anchors when there is no destination, the solution in this case is to provide a fragment identifier, and this is relatively easily accomplished using jQuery. A fragment identifier is added to a URL after the # sign and should correspond with an element with a matching name attribute value.
As with other snippets in this series, this example makes use of the SQL CE 4.0 version of the Northwind database. It assumes that you have a layout page that references jQuery and includes a RenderSection call to an optional section named "script":
The sample page gets data from the database, specifies some columns and an AJAX update container. It includes a loop that runs 30 times, and adds an empty paragraphs each time, which pushes the WebGrid below the bottom of most screens. This forces the scroll bar so that the effectiveness of the solution can be tested. Just before the WebGrid itself, a named anchor has been added. It has been given an identifier of "grid-anchor". The last part of the page is the jQuery. This is examined after the code:
The sorting and paging links appear in the thead and tfoot elements of the grid. The jQuery targets anchor elements in the thead and tfoot only, and alters their href value to include a fragment identifier - grid-anchor, which ensures that when the links are clicked, the user is navigated back to the named anchor position, thus maintaining scroll position. The click event handler is bound to the links using the live command, which ensures that all future links are affected - essential when the target elements are replaced during an AJAX partial update.
A demo containing the source code is available here.