Fork me on GitHub

MvcPager 分页示例 — 删除数据

本示例演示ToPagedList扩展方法的如下功能:当前页索引超出总页数时改变当前页索引为最后一页的页索引,同时获取最后一页的数据。

操作说明:请跳转到最后一页,选中最后一页上所有项的复选框,然后点击“删除选中项”按钮,此时最后一页的所有数据都会被删除,虽然url中的当前页索引未改变,但Model中PagedList对象的CurrentPageIndex已自动变为最后一页的页索引2,同时显示的数据也是最后一页的数据,不会出现空数据或页索引超出范围的错误。

删除
11
12
   当前页索引为:3

View:

@model PagedList<int>
@using (Html.BeginForm())
{
        <table width="90%"><tr><th>值</th><th>删除</th></tr>
        @foreach (var itm in Model)
        {
        <tr><td>@itm</td><td><input type="checkbox" name="val" value="@itm" /></td></tr>
        }
    </table>
        <div><span style="float:right"><input type="submit" value="重置测试(R)" name="resetList" /></span><input type="submit" value="删除选中项(D)" accesskey="D" />
        &nbsp;&nbsp;当前页索引为:@Model.CurrentPageIndex</div>
}
@Html.Pager(Model,new PagerOptions{PageIndexParameterName = "id"})

Controller:

        public ActionResult Delete(int id = 1)
        {
            List<int> list = HttpContext.Cache["TestList"] as List<int>;
            if (list == null)
            {
                list = Enumerable.Range(1, 12).ToList();
                HttpContext.Cache["TestList"] = list;
            }
            return View(list.ToPagedList(id, 5));
        }
        [HttpPost]
        public ActionResult Delete(int id, FormCollection values)
        {
            if (values["resetList"] != null)
            {
                HttpContext.Cache.Remove("TestList");
                return RedirectToAction("Delete");
            }
            var list = HttpContext.Cache["TestList"] as List<int>;
            if (list == null)
                throw new ApplicationException("无法获取缓存的测试数据,请刷新重试");
            int[] delItems = Array.ConvertAll(values["val"].Split(','), i => int.Parse(i));
            list.RemoveAll(delItems.Contains);
            HttpContext.Cache["TestList"] = list;
            return View(list.ToPagedList(id, 5));
        }