要在 .Net Core 3.0 中使用 PagedList,我们将使用https://github.com/dncuug/X.PagedList https://github.com/dncuug/X.PagedList
打开 NuGet 包管理器安装X.PagedList.Mvc.Core
_ViewImports.cshtml
@using X.PagedList.Mvc.Core;
@using X.PagedList;
@using X.PagedList.Mvc.Common
BrandController.cs
public ActionResult Index(int? page)
{
var pageNumber = page ?? 1;
var pageSize = 10; //Show 10 rows every time
var brands = this._UoW.BrandsRepository.GetAll().ToPagedList(pageNumber,pageSize);
return View(brands);
}
索引.cshtml
Change
@model IEnumerable<Stock.Data.Models.Brands>
to
@model IPagedList<Stock.Data.Models.Brands>
改变每一个
@Html.DisplayNameFor(model => model.BrandName)
To
@Html.DisplayNameFor(model => model.First().BrandName)
在 html 表格的末尾添加分页编号,例如
<div class="pull-right">
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index",
new
{
page
}),
new PagedListRenderOptionsBase
{
LiElementClasses = new string[] { "page-item" },
PageClasses = new string[] { "page-link" },
Display = PagedListDisplayMode.IfNeeded
})
</div>
如果您进行搜索或使用其他查询字符串,您必须执行类似的操作:
BrandController.cs
public ActionResult Index(string search,int? page)
{
var pageNumber = page ?? 1;
var pageSize = 10; //Show 10 rows every time
var brands = this._UoW.BrandsRepository.GetAll().Where(b =>
b.BrandName.Contains(search) ||
search == null).ToPagedList(pageNumber, pageSize);
return View(brands);
}
索引.cshtml在 html 表格的末尾添加分页编号,例如
<div class="pull-right">
@Html.PagedListPager((IPagedList)Model, page => Url.Action("Index",
new
{
page,
search = Context.Request.Query["search"]
}),
new PagedListRenderOptionsBase
{
LiElementClasses = new string[] { "page-item" },
PageClasses = new string[] { "page-link" },
Display = PagedListDisplayMode.IfNeeded
})
</div>
为了获得最佳性能使用
.ToPagedList
with IQueryable
所以你每次只会从数据库返回 10 行,而不是整行
Use
public IQueryable<T> GetAll()
{
return this._DbSet;
}
with
this._UoW.BrandsRepository.GetAll().ToPagedList(pageNumber,pageSize);
不使用.ToList()
this._UoW.BrandsRepository.GetAll().ToList().ToPagedList(pageNumber,pageSize);
不使用
public IEnumerable<T> GetAll()
{
return this._DbSet;
}
with
this._UoW.BrandsRepository.GetAll().ToPagedList(pageNumber,pageSize);