Fork me on GitHub

MvcPager demo - Deleting paged items

This sample demonstrates one of the features of ToPagedList extension method that resets the current page index to the total page count and returns the data of the last page when page index is larger than total page count.

Go to the last page and select all items, then click "Delete Selected" button, after all items on the last page are deleted, the current page index and total page count of the underlying IPageList object have been changed to 2 though page index parameter in url is still 3.

ValueDelete
2
3
4
5
6
   Current page index is: 1

View:

        
@model PagedList<int>
@using (Html.BeginForm())
{
    <table class="table table-bordered table-striped">
        <tr><th>Value</th><th>Delete</th></tr>
        @foreach (var itm in Model)
        {
            <tr><td>@itm</td><td><input type="checkbox" name="val" value="@itm" /></td></tr>
        }
    </table>
    <div>
        <span class="pull-right">
            <input type="submit" value="Delete selected(D)" accesskey="D" class="btn btn-primary" />  
            <input type="submit" value="Reset test data(R)" name="resetList" class="btn btn-success" />
        </span>
        Current page index is: @Model.CurrentPageIndex
    </div>
}
@Html.Pager(Model).Options(o => o.SetPageIndexParameterName("id").SetFirstPageRouteName("MvcPager_Default").SetContainerTagName("ul").SetCssClass("pagination").SetCurrentPagerItemTemplate("<li class=\"active\"><a href=\"#\">{0}</a></li>").SetDisabledPagerItemTemplate("<li class=\"disabled\"><a>{0}</a></li>").SetPagerItemTemplate("<li>{0}</li>"))

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("Can not get test data from cache, please retry");
            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));
        }