• 不知道算不算另类的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
  • 相关阅读:
    [saiku] 系统登录成功后查询Cubes
    216. Combination Sum III
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    211. Add and Search Word
    210. Course Schedule II
    分硬币问题
    开始学习Python
  • 原文地址:https://www.cnblogs.com/vbfool/p/3425565.html
Copyright © 2020-2023  润新知