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@using PagedList.Mvc;@{ Layout = null;} Index @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
@foreach (var item in Model) { 省份ID 省份编号 省份名称 } @Html.DisplayFor(modelItem => item.ProvinceID) @Html.DisplayFor(modelItem => item.ProvinceNo) @Html.DisplayFor(modelItem => item.ProvinceName)
运行效果:
引入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
参考资料: