1. 先安裝
NuGet套件 -
PagedList.Mvc
2. Controller
using PagedList;
using PageList.Models;
public ActionResult Index(int page =1)
{
//page用來記憶目前是哪一頁
int currentPage = page < 1 ? 1 : page;
//資料必須先經過排序
var product = db.Product.Where(x => x.Status == 1).OrderBy(x => x.ID);
//分頁資料使用 ToPagedList()
//參數分別是傳入所要分頁的頁碼以及分頁資料量
//此範例就是每一頁會有10筆資料
var PageResult = product.ToPagedList(currentPage, 10);
return View(PageResult);
}
3. View
需要
using PagedList.Mvc 和
PagedList
取得分頁:
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page = page}))
//設定PagedListRenderOptions 可更改樣式
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page = page})
,PagedListRenderOptions.MinimalWithPageCountText)
//也可以自由設定顯示物件
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page = page}),
new PagedListRenderOptions {
DisplayLinkToIndividualPages=false,
DisplayLinkToFirstPage =PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage= PagedListDisplayMode.IfNeeded,
DisplayLinkToNextPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToPreviousPage = PagedListDisplayMode.IfNeeded,
DisplayPageCountAndCurrentLocation = true,
PageCountAndCurrentLocationFormat ="第{0}頁 / 共{1}頁"
})
https://github.com/TroyGoode/PagedList