X.pagedList的使用

 

此為 X.pagedList 搭配 bootstrap 4 範例,

資料庫的部份,我則借用北風資料庫

第一步先於 package manager console 安裝 X.pagedList,指令如下

Install-Package X.PagedList.Mvc -Version 7.2.0

可能需要等個幾分鐘才安裝完成。

 

Model 端的前期準備就不談了,接下來於 controller 端撰寫程式如下

using System.Linq;
using System.Web.Mvc;

using WebApplication1.Models;
using X.PagedList;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        private NorthwindEntities db = new NorthwindEntities();
        private int pageSize = 5;

        public object Index(int? page)
        {
            var products = db.Products.OrderBy(x => x.ProductID);

            var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
            var onePageOfProducts = products.ToPagedList(pageNumber, pageSize); // will only contain 5 products max because of the pageSize

            ViewBag.OnePageOfProducts = onePageOfProducts;
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

View 端程式如下

@{
    ViewBag.Title = "Product Listing";
}

@using X.PagedList.Mvc;
@using X.PagedList;

<!– loop through each of your products and display it however you want. we're just printing the name here –>
<h2>List of Products</h2>
<ul>
@foreach (var product in ViewBag.OnePageOfProducts)
{
<li>@product.ProductName</li>
}
</ul>

<!– output a paging control that lets the user navigation to the previous page, next page, etc –>
@Html.PagedListPager((IPagedList)ViewBag.OnePageOfProducts,
page => Url.Action("Index", new { page }),
new PagedListRenderOptions
{
ContainerDivClasses = new[] { "" },
LiElementClasses = new[] { "page-item" },
PageClasses = new[] { "page-link" },
MaximumPageNumbersToDisplay = 5
})

X.pagedList 提供了 PagedListRenderOptions 讓開發者做客制化,

這對開發者來說非常方便。

 

2018/11/08:注意,X.pagedList 7.6.0 版本有問題,不要去升級成該版本。

 

參考資料:

dncuug/X.PagedList

LINQ自學筆記-語法應用-分頁方法-Take、Skip、TakeWhile、SkipWhile