To keep (or to say it better, to recover) the page scrollbar position after a postback is definitely a feature any form-containing page should have. This used to be a trival task for any ASP.NET developer, who could just by add a simple configuration parameter to their code:
On web.config level: <pages maintainScrollPositionOnPostBack="true" />
On page level: <%@ Page MaintainScrollPositionOnPostback="true" %>
On code-behind level: Page.MaintainScrollPositionOnPostBack = true;
Unfortunately all these methods, other than being unavailable with Razor, aren't working anymore with any recent non-IE browser. Sure, it's still possible to detect and configure the behavior of each one of them by using the ASP.NET Browser Definition Files accordingly, but in order to achieve better results it's advised to adopt a centralized, versatile solution. Here's a simple script based on the popular jQuery framework who does the trick in a cross-browser compatible way:
For WinForms:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<asp:HiddenField runat="server" ID="hfPosition" Value="" /> <script type="text/javascript"> $(function () { var f = $("#<%=hfPosition.ClientID%>"); window.onload = function () { var position = parseInt(f.val()); if (!isNaN(position)) { $(window).scrollTop(position); } }; window.onscroll = function () { var position = $(window).scrollTop(); f.val(position); }; }); </script> |
For Razor (and also for any web page, since it's pure HTML+JS):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<input id="hfPosition" name="hfPosition value="" /> <script type="text/javascript"> $(function () { var f = $("#hfPosition"); window.onload = function () { var position = parseInt(f.val()); if (!isNaN(position)) { $(window).scrollTop(position); } }; window.onscroll = function () { var position = $(window).scrollTop(); f.val(position); }; }); </script> |
Needless to say, in order to make these scripts work you have to place the input element on top (asp:HiddenField for the WinForms one) inside the form element who will handle the Postback.
Thanks Ryan..the code is working like a charm :) Can u please explain how its getting the value
The value gets updated by the javascript code every time the user scrolls up or down (“onscroll” event) and put in the hidden input field, so that it will be available upon each postback. That same value – if present – will be fetched by javascript (in the “onload” event) and then used to update the browser’s scroll position accordingly. That’s about it.