如何在asp.net中回页后保持页面滚动位置

时间:2011-09-12 22:38:37

标签: javascript c# asp.net ajax

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

不起作用,我哪里出错

    <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" AutoGenerateColumns="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>

我试图让页面在每5秒后页面刷新并且页面返回顶部时保持在相同的位置。我试过Page MaintainScrollPositionOnPostback =“true”。它没用,我尝试使用Ajax但不知道如何使用它。有人可以帮助我如何使用Ajax。

12 个答案:

答案 0 :(得分:21)

在您的设计页面上尝试以下代码。它对我来说很好..

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

答案 1 :(得分:3)

MaintainScrollPositionOnPostback仅适用于IE。要执行此操作,您可以滚动自己的客户端脚本,也可以在页面/表单的不同部分使用锚点链接。

这里有类似的问题:

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?

答案 2 :(得分:2)

听起来糟糕的UI(每5秒页面刷新一次)的廉价修复方法是在地址栏中添加“#”和要保留的元素的ID,但会自动滚动到ID链接元素的顶部。

如果这是一个商业产品并且您赶时间,我建议您查看JQuery的ajax实现并完全取消这些重新加载。

它可能像以下一样简单:

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

如果这看起来很奇怪,那只是一个对象文字被提供给JQuery对象的ajax方法。分配给'complete'的函数在收到http响应时触发,该函数作为参数'data'提供给函数,该参数在.ajax方法的内部建立。

答案 3 :(得分:2)

<%@ Page MaintainScrollPositionOnPostback="true" %>因为页面声明将保持滚动位置

答案 4 :(得分:1)

从性能角度看,UpdatePanels非常糟糕。我会用jquery做这个并完全避免回发。

$.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);
    }

});

如果这是一个选项,请根据本教程设置要读取的URL:

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

如果您不想使用jquery,您仍然可以使用MS AJAX,只需跳过这些更新面板即可。 http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm

答案 5 :(得分:1)

在后面的代码中尝试这个:

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

Posdata:我用C#试了一下。

答案 6 :(得分:0)

@{
    
}

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

您可以使用此功能在回发后保持滚动位置。

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

答案 7 :(得分:0)

对于其他正在努力解决这个问题的人。最简单的解决方案是保持整个窗口的滚动位置

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

    });

广告包括开始和结束请求。在开始请求时,使用Jquery获取窗口滚动位置。在结束请求时,只需滚动到该位置即可。

答案 8 :(得分:0)

添加此行

<%@ Page MaintainScrollPositionOnPostback="true" %>

答案 9 :(得分:0)

网络上有这个问题的答案,并且个人都没有工作,因为对我来说Firefox会尝试恢复之前的滚动位置(错误地),触发window.scroll事件,这会覆盖我的隐藏字段,其位置错误,我的scrollTo将会读取该字段。 (我有来自回发的网格视图,然后是自动折叠某些行。)

所以这是另一个解决这个问题的方法 - 我决定我只想在提交后恢复滚动位置,而不是刷新,所以这就足够了:

ASPX页面:

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

出于某种原因,在浏览器刷新时,我的隐藏输入没有重置为零,所以这有时表现得很奇怪。我很想知道这是做什么的,我认为它是Firefox,因为它不会发生在IE上,但是生命太短[他说...已经下载了一半的互联网,花了几个小时......]。

答案 10 :(得分:0)

如果回发是由按钮引起的,则可以尝试以下操作:

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

答案 11 :(得分:-3)

<pages maintainScrollPositionOnPostBack="true">