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
  • 相关阅读:
    读写锁机制原理
    jvm
    (WPF) 再议binding:点击User Control时,User Control变换颜色或做其他的处理。
    (WF)
    (C# ) 解析XML。
    (C#) 调用执行批处理文件
    (WPF, Service) 删除注册表中的USB Enum值.
    (C#) 文件操作
    (C#) Parse xml 时, 返回的node值总是null。
    (PowerShell) Managing Windows Registry
  • 原文地址:https://www.cnblogs.com/vbfool/p/3425565.html
Copyright © 2011-2022 走看看