ASP.NET MVC中進行分頁的方式有多種,在NuGet上有提供使用PagedList、PagedList.Mvc進行分頁。
1. 通過NuGet引用PagedList.Mvc
在安裝引用PagedList.Mvc的同時會安裝引用PagedList。
2. PagedList.Mvc基本使用
ProvinceController.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcExample.Models; using PagedList; namespace MvcExample.Controllers { public class ProvinceController : Controller { private MvcExampleContext ctx = new MvcExampleContext(); public ActionResult Index(int page = 1) { return View(ctx.Provinces.OrderBy(p => p.ProvinceID).ToPagedList(page, 10)); } protected override void Dispose(bool disposing) { ctx.Dispose(); base.Dispose(disposing); } } }
Index.cshtml:
@model PagedList.IPagedList<MvcExample.Models.Province> @using PagedList.Mvc; @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <style type="text/css"> ul.pagination { margin: 0; } .pagination li { list-style-type: none; float: left; min-width: 15px; } </style> </head> <body> <table> <tr> <th> 省份ID </th> <th> 省份編號 </th> <th> 省份名稱 </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ProvinceID) </td> <td> @Html.DisplayFor(modelItem => item.ProvinceNo) </td> <td> @Html.DisplayFor(modelItem => item.ProvinceName) </td> </tr> } </table> @Html.PagedListPager(Model, page => Url.Action("Index", new { page })) </body> </html>
執行效果:
引入PagedList.Mvc分頁之後生成的分頁Html程式碼:
分頁執行的SQL語句:
SELECT TOP (10) [Extent1].[ProvinceID] AS [ProvinceID], [Extent1].[ProvinceNo] AS [ProvinceNo], [Extent1].[ProvinceName] AS [ProvinceName] FROM ( SELECT [Extent1].[ProvinceID] AS [ProvinceID], [Extent1].[ProvinceNo] AS [ProvinceNo], [Extent1].[ProvinceName] AS [ProvinceName], row_number() OVER (ORDER BY [Extent1].[ProvinceID] ASC) AS [row_number] FROM [dbo].[Province] AS [Extent1] ) AS [Extent1] WHERE [Extent1].[row_number] > 10 ORDER BY [Extent1].[ProvinceID] ASC
參考資料: