如何使用 PagedList.Mvc 分页

时间:2023-03-09 23:29:05
如何使用 PagedList.Mvc 分页

刚开始找PagedList分页不是例子太复杂,就是写的过于简略,由于对于MVC的分页不太了解,之前使用的都是Asp.Net 第三方控件 + 数据库存储过程分页。还是老外写的例子简捷,https://github.com/TroyGoode/PagedList  。

1、本实例采用MVC + EF 框架,至于怎么配置,就不再这里说了。

如何使用 PagedList.Mvc 分页

2、安装 "PagedList.Mvc"的同时 “PagedList”会自动安装

路径:解决方案资源管理器 -> 选中工程名,点击右键 -> 管理NuGet程序包

如何使用 PagedList.Mvc 分页

首先选中联机,再选中 “PagedList.Mvc” 进行安装

如何使用 PagedList.Mvc 分页

3、在控制器HomeController.cs 中添加代码

3.1 添加命名空间

    

using PagedList.Mvc;
using PagedList;

3.2 在Index方法中添加代码

         #region 0.7 查询文章列表--分页 + ActionResult Index()
/// <summary>
/// 查询 文章 列表 并分页
/// </summary>
/// <returns></returns>
public ActionResult Index(int?page)
{
var query = db.BlogArticles.Where(d => d.AIsDel == false).OrderByDescending(d => d.AId) ;
var pageNumber = page ?? ; // if no page was specified in the querystring, default to the first page (1)
var onePageOfProducts = query.ToPagedList(pageNumber, ); // will only contain 25 products max because of the pageSize
ViewBag.OnePageOfProducts = onePageOfProducts; return View();
}
#endregion

4、在视图Index.cshtml中添加代码
        4.1 在添加代码前,现在编译一下代码,否在在视图中添加命名空间会提示”缺少引用命名空间“的语法错误,解决方案资源管理器->选中工程点击右键->重新生成

4.2  添加命名空间

@using PagedList;
@using PagedList.Mvc;

4.3  显示文章列表

 <!DOCTYPE html>

 <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#tbList
{
border:1px solid #0094ff;
border-collapse:collapse;
margin:10px auto;
width:800px;
}
#tbList th,td
{
border:1px solid #0094ff;
padding:10px;
}
</style>
<script type="text/javascript">
function del(Aid) {
if (confirm("确定要删除吗?"))
window.location = "/Home/Del/" + Aid;
}
</script>
</head>
<body>
<table id="tbList">
<tr>
<th>id</th>
<th>标题</th>
<th>分类</th>
<th>状态</th>
<th>时间</th>
<th>操作</th>
</tr>
@foreach (var a in ViewBag.OnePageOfProducts)
{
<tr>
<td>@a.AId</td>
<td>@a.ATitle</td>
<td>@a.BlogArticleCate.Name</td>
<td>@a.Enumeration.e_cname</td>
<td>@a.AAddtime</td>
<td>
<a href="javascript:del(@a.AId)">删</a>
<a href="/Home/Modify/@a.AId">改</a>
</td>
</tr>
}
</table>

4.4  分页

   <div  style = "margin:10px auto; text-align:center;">
@Html.PagedListPager((IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page }))
</div>
</body>
</html>