Reset scroll position after Async postback - ASP.NET

*爱你&永不变心* 提交于 2019-11-27 04:19:49
Zhaph - Ben Duguid

As you're using UpdatePanels you're going to need to hook into the ASP.NET AJAX PageRequestManager

You'll need to add a method to the endRequest event hooks that are:

Raised after an asynchronous postback is finished and control has been returned to the browser.

So you'd have something like:

<script type="text/javascript">
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(pageLoaded);

  function pageLoaded(sender, args) {
     window.scrollTo(0,0);
  }
</script>

Which will force the browser to scroll back to the top of the page once an update request has completed.

There are other events you could hook into instead of course:

beginRequest // Raised before the request is sent
initializeRequest // Raised as the request is initialised (good for cancelling)
pageLoaded // Raised once the request has returned, and content is loaded
pageLoading // Raised once the request has returned, and before content is loaded

The beauty of asynchronous post-backs is that the page will maintain the scroll height without you having to set MaintainScrollPosition, as there is no "full page reload" happening, in this case you actually want that effect to happen, so you will need to manually create it.

Edit to respond to updated question

Ok, so if you need to only reset the postion on certain button presses you'll need to do something like this:

Start by hooking into the BeginRequest instead/as well:

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);

This is because in the args parameter you get access to:

args.get_postBackElement().id

Which will tell you the id of the button that started the whole event - you can then either check the value here, and move the page, or store it in a variable, and query it in the end request - being aware of race conditions, etc where the user clicks another button before your original update completes.

That should get you going with any luck - there's quite a few examples around this on Working with PageRequestManager Events

Here is the perfect solution to reset scroll bar position to TOP in AJAX

Client Side Code

function ResetScrollPosition()
{
    setTimeout("window.scrollTo(0,0)", 0);
}

Server Side Code

ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "ResetScrollPosition();", true);

Only,window.scrollTo(0,0) will not work. Ajax will take precedence in this case so you have to use setTimeout function with that.

Here is the following solution I developed based on this source

ASP.NET Webform

<script language="javascript" type="text/javascript">
   function SetScrollEvent() {
      window.scrollTo(0,0);
   }
</script> 

<asp:GridView id="MyGridView" runat="server" OnRowDataBound="MyGridView_OnRowDataBound">
    <Columns>
        <asp:CommandField ButtonType="Link" ShowEditButton="true" />
    </Columns>
</asp:GridView>

ASP.NET Webform code behind

protected void MyGridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType.Equals(DataControlRowType.DataRow))
    {
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
            foreach(Control control in cell.Controls)
            {
                LinkButton lb = control as LinkButton;

                if (lb != null && lb.CommandName == "Edit")
                    lb.Attributes.Add("onclick", "SetScrollEvent();");
            }
        }
    }
}

Are you using asp.net AJAX? If so there are two very useful events in the client libraries beginRequest and endRequest, one of the problems with partial/async postbacks, is that the general page hasnt got a clue what you are doing. the begin and endrequest events will allow you to maintain scroll position at the client, you could have a var in js that is set to the scroll position on beginrequest, then on end request you can reset whichever element's scrollTop you require.. i'm sure ive seen this done before but cant find a link. ill post if i find an example

taken from this tutorial:

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

We set MaintainScrollPositionOnPostback=true

Then if we need to reset scroll position call the method:

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 

Have you set the page property MaintainScrollPosition? Not sure if that would be any different if you do an Async Postback or not.

Edit: One thing you could attempt is to set focus on a particular item near the top of your page, that may help and be a dirty work around.

I use a hidden Input called hScrollTop that I set before the asp.net Form is posted back. Then, when the page loads, it sets the scrollTop according to the hidden input's value.

Try this code on a new page.

<div style="height:500px"></div>

<form id="Form1" runat=server onsubmit="javascript:saveScrollTop();">
    <input type=submit value="Submit" runat=server>
    <input type="hidden" id="hScrollTop" runat=server>
</form>

<div style="height:1000px"></div>

<script language="javascript">
    function saveScrollTop() {
        document.getElementById("<%= hScrollTop.ClientID %>").value = document.body.scrollTop;
        return true;
    }

    window.onload = function() {
        document.body.scrollTop = document.getElementById("<%= hScrollTop.ClientID %>").value;
    }

</script>
Dmitriy
Page.RegisterStartupScript("MyScript", "<script language=javascript>setTimeout('window.scrollTo(0,0)', 0);</script>");

Put the above to the function that you want to tell to go to the top of page. Like when the page is not valid, have that there and it will add temporary javascript to shoot you to the top of the page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!