zoukankan      html  css  js  c++  java
  • 不知道算不算另类的ASP.NET MVC4 Ajax分页

    以往用Ajax来实现无刷新分页,用户一按F5,页数就记不住了,点了一个链接也是同一个问题,再想回退回来,就回到第一页了。上次看到一篇文章,说到window.location.hash的用途,于是萌生了这么一个想法,把这个用来保存Ajax的状态。

    大概的实现思路是这样的:页面监听window.onhashchange事件,然后通过Ajax向后台请求分页内容,再替换掉原来的分页结果。当然这个方法要一开始也执行一下,用来应对回退功能。

    代码大概如下:  

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <div id="MainDiv"></div>
    
    @section scripts{
        <script>
            function GoToPage(PageIndex) {
                $.ajax({
                    url: '@Url.Action("GetPage")',
                        data: { Page: PageIndex },
                        success: function (data) {
                            $("#MainDiv").html(data);
                        }
                    });
                }
    
                function GetLocationHash() {
                    //var IsGotoPage = false;
                    var PageIndex = 1;
                    var m = window.location.hash.slice(1).split("&");
                    for (var i = 0; i < m.length; i++) {
                        var item = m[i];
                        if (item.indexOf("Page=") > -1) {
                            PageIndex = item.slice(5);
                        }
                    }
                    GoToPage(PageIndex);
                    //alert(values);
                }
                window.onhashchange = GetLocationHash;
                GetLocationHash();
        </script>
    }
    Index.cshtml
    @model IEnumerable<dynamic>
    <table>
        <thead>
            <tr>
                <th>编号</th>
                <th>内容</th>
                <th>日期</th>
                <th>操作</th>
            </tr>
        </thead>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.ID
                </td>
                <td>
                    @item.Content
                </td>
                <td>
                    @item.UpdateDate
                </td>
                <td>
                    @Html.ActionLink("查看", "Detail", new { ID = item.ID })
                </td>
            </tr>    
        }
    </table>
    <ul>
        @for (int i = 1; i <= ViewBag.PageCount; i++)
        {
            if (i == ViewBag.PageIndex)
            {
            <li style="display: inline-block"><span>@i</span></li>    
            }
            else
            {
            <li style="display: inline-block"><a href="#Page=@i">@i</a></li>
            }
    
        }
    </ul>
    GetPage.cshtml
  • 相关阅读:
    UVa532 Dungeon Master 三维迷宫
    6.4.2 走迷宫
    UVA 439 Knight Moves
    UVa784 Maze Exploration
    UVa657 The die is cast
    UVa572 Oil Deposits DFS求连通块
    UVa10562 Undraw the Trees
    UVa839 Not so Mobile
    327
    UVa699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/vbfool/p/3425565.html
Copyright © 2011-2022 走看看