Fork me on GitHub

MvcPager demo - Implementing IPagedList interface

This sample demonstrates how to inplement IPagedList interface that makes custom object pageable.

11
12
13
14
15
First Prev 1 2 3 4 5 6 7 8 9 10 ... Next Last 

View:

        
@model MyPagedList<int>
<table class="table table-bordered table-striped">
    @foreach (var itm in Model.PagedItems)
    {
        <tr><td>@itm</td></tr>
    }
</table>
@Html.Pager(Model,new PagerOptions{PageIndexParameterName = "id",PagerItemTemplate = "{0}&nbsp;"})

Model:

    public class MyPagedList<t> :IPagedList<t>
    {
        public MyPagedList(IEnumerable<t> currentPageItems,int pageIndex, int pageSize, int totalItemCount)
        {
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
            TotalItemCount = totalItemCount;
            PagedItems = currentPageItems.ToList();
        }
        public MyPagedList(IEnumerable<t> allItems, int pageIndex, int pageSize)
        {
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
            var items = allItems as IList<t> ?? allItems.ToList();
            TotalItemCount = items.Count();
            int startIndex = (pageIndex - 1)*pageSize;
            PagedItems = items.Skip(startIndex).Take(pageSize).ToList();
        }
        public List<t> PagedItems { get; set; } 
        public int CurrentPageIndex { get; set; }
        public int PageSize { get; set; }
        public int TotalItemCount { get; set; }
        public IEnumerator<t> GetEnumerator()
        {
            return PagedItems.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

Controller:

        
        public ActionResult IPagedList(int id=1)
        {
            MyPagedList<int> list=new MyPagedList<int>(Enumerable.Range(1,88),id,5);
            return View(list);
        }