ASP.NET MVC 4使用PagedList.Mvc分页

时间:2022-01-01 19:47:22

ASP.NET MVC中进行分页的方式有多种,在NuGet上有提供使用PagedList、PagedList.Mvc进行分页。

  1. 通过NuGet引用PagedList.Mvc

ASP.NET MVC 4使用PagedList.Mvc分页

  在安装引用PagedList.Mvc的同时会安装引用PagedList。

  2. PagedList.Mvc基本使用

  ProvinceController.cs:

ASP.NET MVC 4使用PagedList.Mvc分页
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);
}
}
}
ASP.NET MVC 4使用PagedList.Mvc分页

  Index.cshtml:

ASP.NET MVC 4使用PagedList.Mvc分页
@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>
ASP.NET MVC 4使用PagedList.Mvc分页

  运行效果:

ASP.NET MVC 4使用PagedList.Mvc分页

  引入PagedList.Mvc分页之后生成的分页Html代码:

ASP.NET MVC 4使用PagedList.Mvc分页

   分页执行的SQL语句:

ASP.NET MVC 4使用PagedList.Mvc分页
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
ASP.NET MVC 4使用PagedList.Mvc分页