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

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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

Method 3

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.

Method 4

I’ve found that setting the property:

maintainScrollPositionOnPostBack="true"

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

Method 5

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

Method 6

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.

Method 7

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();

Method 8

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().


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x