开发者

How to maintain page scroll position after a page postback in asp.net [duplicate]

This question already has answers here: Prevent page scrolling after postback and maintain position (8 answers) Closed 2 years ago.
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
    <meta http-equiv="refresh" content="4" />   
 <script type="text/javascript">

    var xPos1, yPos1;

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoading(pageLoadingHandler);
    prm.add_pageLoaded(pageLoaded);
    function pageLoaded(sender, args) {

        $get('<%=Panel_Users.ClientID %>').scrollLeft = xPos1;
        $get('<%=Panel_Users.ClientID %>').scrollTop = yPos1;
    }
    function pageLoadingHandler(sender, args) {
        xPos1 = $get('<%=Panel_Users.ClientID %>').scrollLeft
        yPos1 = $get('<%=Panel_Users.ClientID %>').scrollTop;
    }
    </script>
</asp:Content>

Doesn't work, where am I going wrong

    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"  />    

<div style="height: 504px; width: 941px;">
                 <asp:Panel runat="server" ID="Panel_Users" ScrollBars="Auto" Style="z-index: 1; left: 748px;
                     top: 621px; position: absolute; height: 250px; width: 287px">
                     <asp:UpdatePanel UpdateMode="Conditional" ID="UpdatePanel1" runat="server">
                         <ContentTemplate>
                             <asp:GridView ID="Grid_UserTable" runat="server" Style="z-index: 1; left: 2px; top: 5px;
                                 position: absolute; height: 152px; width: 243px" BorderColor="#666666" AutoGenerateColumn开发者_如何学Cs="False"
                                 OnRowDataBound="MyGrid_RowDataBound">
                                 <Columns>
                                     <asp:TemplateField HeaderText="Status">
                                         <ItemTemplate>
                                             <asp:Image ID="Status" runat="server" />
                                         </ItemTemplate>
                                     </asp:TemplateField>
                                     <asp:BoundField DataField="TimeReceived" HeaderText="TimeReceived" InsertVisible="False"
                                         ReadOnly="True" SortExpression="TimeReceived" />
                                     <asp:BoundField DataField="TimeRead" HeaderText="TimeRead" SortExpression="TimeRead" />
                                     <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                                 </Columns>
                             </asp:GridView>
                         </ContentTemplate>
                     </asp:UpdatePanel>
                 </asp:Panel>
             </div>

I am trying to make the page stay at the same position when the page refreshes after every 5 seconds and the page goes to top. I tried Page MaintainScrollPositionOnPostback="true" . It didn't work, I tried using Ajax but have no idea how to use it. Can someone help me how to do it with Ajax.


Try the following code on your design page..It works fine for me..

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="frmName.aspx.vb" Inherits="frmName" MaintainScrollPositionOnPostBack = "true" %>


The MaintainScrollPositionOnPostback only works in IE. To do this you can either roll your own client script or use anchor links on different sections of your page/form.

Similar questions here:

MaintainScrollPositionOnPostback is not working - how to debug?

MaintainScrollPositionOnPostback not working with javascript:__doPostBack

maintainScrollPositionOnPostback="true" does not work globally after setting in web.config ,but works in page level,what should I do?


<%@ Page MaintainScrollPositionOnPostback="true" %> as the page declaration will keep the scroll position as it is


A cheap fix for what sounds like awful UI (page refreshes every 5 seconds) would be to add '#' and the id of the element you want to keep in view to the URL in the address bar but that will automatically scroll to the top of the ID-linked element.

If this is a commercial product and you're in a hurry I'd recommend checking out JQuery's ajax implementation and knock off those reloads altogether.

It may be as simple as a line like:

  $.ajax(
    {
      url:"/thisPath/requestPath",
      complete:function(data){
      //apply data (the http-response) to HTML
    }
  );

If that looks bizarre to you, it's just an object-literal being fed to the JQuery objects ajax method. The function assigned to the 'complete' fires when the http-response is received which is fed to the function as the argument 'data' which is established on the inside of the .ajax method.


Try this in the code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        Page.MaintainScrollPositionOnPostBack = true;
    }
}

Posdata: I tried it with C#.


UpdatePanels are horrible from a performance standpoint. I would do this with jquery and avoid the postbacks completely.

$.ajax({
    url: "/path/to/url/that/returns/users",
    type: "POST",
    dataType: "json",
    data: {},
    success: function(data, status, xhttp)
    {
        var html = "<table>";
        for ( var i = 0; i < data.length; i++ )
        {
            html += "<tr>";
            html += "<td></td>"; // build up table cells
            html += "</tr>";
        }
        html += "</table>";
        $("#NameOfDivToPutTableIn").html(html);
    }

});

If this is an option, set up the url to read from based on this tutorial:

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

If you don't want to use jquery, you can still use MS AJAX, just skip those update panels. http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm


@{
    
}

<html>

<head>
<script type="text/javascript">

window.onload = function () {
   var div = document.getElementById("dvScroll");
   var div_position = document.getElementById("div_position");
    var position = parseInt(@Request.Form("div_position"));
    if (isNaN(position)) {
        position = 0;
    }

    div.scrollTop = position;
    div.onscroll = function () {
        div_position.value = div.scrollTop;
    };
};

</script>
</head>

<body>

<div id="dvScroll" style="overflow-y: scroll; height: 260px; width: 300px">
    1. This is a sample text
    <br />
    2. This is a sample text
    <br />
    3. This is a sample text
    <br />
    4. This is a sample text
    <br />
    5. This is a sample text
    <br />
    6. This is a sample text
    <br />
    7. This is a sample text
    <br />
    8. This is a sample text
    <br />
    9. This is a sample text
    <br />
    10. This is a sample text
    <br />
    11. This is a sample text
    <br />
    12. This is a sample text
    <br />
    13. This is a sample text
    <br />
    14. This is a sample text
    <br />
    15. This is a sample text
    <br />
    16. This is a sample text
    <br />
    17. This is a sample text
    <br />
    18. This is a sample text
    <br />
    19. This is a sample text
    <br />
    20. This is a sample text
    <br />
    21. This is a sample text
    <br />
    22. This is a sample text
    <br />
    23. This is a sample text
    <br />
    24. This is a sample text
    <br />
    25. This is a sample text
    <br />
</div>

<hr />
<form method="post">
<input type="hidden" id="div_position" name="div_position" />
<input type="submit" value="Cool" />
</form> 
</body>
</html>

You can use this to maintain scroll Position after postback.

Source: http://www.aspsnippets.com/Articles/Maintain-Scroll-Position-of-DIV-on-PostBack-in-ASPNet.aspx


For someone else struggling with this. Easiest solution is to keep the scroll location of the entire window

  var xPos, yPos;

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (evt, args) {
        window.scrollTo(xPos , yPos);
    });


    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function (evt, args) {
        xPos = $(window).scrollLeft();
        yPos = $(window).scrollTop();

    });

Ad both begin and end request. On begin request get the windows scroll position using Jquery. On end request just scroll to that location.


There are answers all over the net to this problem, and personally none of them worked, as for me Firefox would attempt to recover the previous scroll position (wrongly), trigger the window.scroll event, which would overwrite my hidden field with its wrong position, which my scrollTo would then read. (I have gridviews coming from postbacks followed by automatic collapsing of some rows.)

So here's yet another solution to this problem - I decided I only want to recover the scroll position after a submit, not a refresh, so this was adequate:

ASPX page:

<form runat="server" onsubmit="$('#hfScroll').val($(window).scrollTop()); return true;">
    <input type="hidden" id="hfScroll" value="0" />

Javascript:

function restoreScroll()
{
    var position = parseInt($('#hfScroll').val());
    if (!isNaN(position)) {
        $(document).scrollTop(position);
    }
};
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(restoreScroll);

For some reason, on browser refresh my hidden input is not reset to zero, so this does behave odd sometimes. I would love to know what's doing this, I think it is Firefox as it doesn't happen on IE, but life's too short [he says...having downloaded half the internet and spent hours on this..].


If the post back is caused by a button, you can try this:

ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(button);


<pages maintainScrollPositionOnPostBack="true">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜