Fork me on GitHub

MvcPager 分页示例 — 实现IPagedList接口

该示例演示如何通过实现IPagedList<T>接口而不是使用内建的PagedList<T>来自下定义分页数据对象。

31
32
33
34
35
首页 上页 ... 2 3 4 5 6 7 8 9 10 11 ... 下页 尾页 

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);
        }