How can I prevent a page to jump to top position after failed validation?
Asked Answered
A

8

26

I have a simple aspx page with a few TextBoxes and a submit button. Some fields are required and below the button is a ValidationSummary. The complete form is larger than screen height so one has to scroll down to reach the submit button. If I don't fill all required fields and click on submit validation fails as expected and the validation summary displays some info messages below the button. Validation happens on the client and no postback occurs.

So this all works as wished. But disturbing is that the page moves ("jumps") to top position when I click on the submit button. To see the validation summary one has to move down the page again.

I've tried to set the ShowSummary property to false (which doesn't make much sense): The validation still works (no postback) but in this case the page does not move to top position. So the problem seems to depend on rendering the validation texts.

Is there a way to prevent this page jump?

Thank you in advance!

Update:

The behaviour I described above doesn't seem to be browser dependent. I've tested in five different browsers and it's everywhere the same.

Airy answered 10/4, 2010 at 12:50 Comment(1)
See also #699671Durazzo
A
34

I've asked the question on asp.net (http://forums.asp.net/p/1545969/3779312.aspx) and got replies with two solutions. The better one is this piece of Javascript which maintains the scroll position:

<script type="text/javascript">
    window.scrollTo = function( x,y ) 
    {
        return true;
    }
</script>

This is only to put on the page and nowhere to call.

The other solution is similar to RioTera's proposal here (using MaintainScrollPositionOnPostBack) but adds EnableClientScript="false" to the Validators to force a postback. It works too, but the price is an artificial postback.

Airy answered 11/4, 2010 at 21:10 Comment(2)
This is great. Thanks for posting... Quick question: What if JavaScript is disabled?Journey
@nicorellius: Then it won't work. I think Page.MaintainScrollPositionOnPostBack needs enabled Javascript as well. I don't know if there is any solution without Javascript.Airy
M
24

You can use the the Page property MaintainScrollPositionOnPostBack :

In the code-behind:

Page.MaintainScrollPositionOnPostBack = true;

or in your webform:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" MaintainScrollPositionOnPostback="true" %>
Moskow answered 10/4, 2010 at 13:11 Comment(2)
It does not work since I don't have a postback. Validation fails on client side and this "page jump" seems to be a pure client side behaviour.Airy
it doesn't work in the page directive on a master page. In this case, you can set it in the web.config file in system.web/pages on the attribute maintainscrollPositionOnPostBackShadchan
T
6

Try setting the page focus Page.SetFocus(control); I have an insert button which adds an extra row to my gridview, which is one of many items on a page so I can add Page.SetFocus(control) as the last method in my btnInsert_Click event.

Tees answered 19/3, 2012 at 17:30 Comment(1)
Thanks. This one worked for me. using MaintainScrollPositionOnPostback made the page flash. I found control.Focus() was a bit smoother than Page.SetFocus(control).Eyestalk
M
4

I've found that setting the property:

maintainScrollPositionOnPostBack="true"

in your Web.config <pages> section works well.

Masonmasonic answered 8/6, 2015 at 18:10 Comment(0)
S
1

The page flickers because the whole page is posted back to the server and the content is sent back from server again. You need to use UpdatePanel tag to surround the place you want to refresh. It will only postback the information which is inside the tag

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <!-- Place updatable markup and controls here. -->
</ContentTemplate>
</asp:UpdatePanel>

Read http://msdn.microsoft.com/en-us/library/bb386573(v=vs.100).aspx#CodeExamples

Spurgeon answered 14/1, 2013 at 23:5 Comment(0)
J
1

Unfortunately MantainScrollPositionOnPostback doesn't work anymore on modern browsers. For a cross-browser-compatible solution you can use this snippet (requires jQuery):

<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>

See also my answer here.

Jaehne answered 16/12, 2014 at 13:47 Comment(0)
N
0

I'm using MVC5 and the only way to stop the jump was with the JQuery code below.

I've tested the solution on Safari, Chrome, Mozilla, Internet Explorer and Opera.

$(document).scrollTop($('form#formCheckout').offset().top);
    event.stopPropagation();
    event.preventDefault();
Neologize answered 17/7, 2015 at 3:16 Comment(0)
L
0

Disabling window.scrollTo is not a good solution because it could unknowingly break other scripts on the page.

Instead, on your ValidationSummary, set the ClientIDMode to Static and define a very unique ID, e.g.:

<asp:ValidationSummary id="VeryUniqueValidationSummaryID"
    ClientIDMode="Static" ...

Next, on your submit button, set OnClientClick to scroll the validation summary back into view, like this:

<asp:LinkButton ID="MyButton"
    OnClientClick="ScrollToValidationSummary();"

The Javascript function first checks if the page is valid. If not, then it scrolls the validation summary back into view after a brief timeout:

function ScrollToValidationSummary() {
    if (!Page_ClientValidate()) {
        setTimeout(function () {
            var summary = document.getElementById('VeryUniqueValidationSummaryID');
            summary.scrollIntoView();
        }, 500);
     }
 }

Due to setTimeout not firing at the right time, occasionally the scroll position may still be off. But it should be correct for the vast majority of users.

Note: If you are using a ValidationGroup, you need to call Page_ClientValidate("ValidationGroupName") instead of Page_ClientValidate().

Loisloise answered 8/11, 2020 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.