How to Add Pagination in Asp.net Core MVC
Here, In this blog post, I have shared you the solution for how to add pagination in asp.net core mvc. This can be implemented in every dotnet version.
Steps to Add Pagination in Asp.net Core MVC
1. Install Nuget Package: X.PagedList.Mvc.Core
2. Add paging functionality to the Index method
public async Task<IActionResult> Index(int? page)
{
var listOfPostsVM = new List<PostViewModel>();
listOfPostsVM = _context.Posts!.ToList();
int pageSize = 5;
int pageNumber = (page ?? 1);
return View(await listOfPostsVM.ToPagedListAsync(pageNumber,pageSize));
}
3. Add paging links to the Student index view
@model IPagedList<PostViewModel>
@using X.PagedList
@using X.PagedList.Mvc.Core
@using X.PagedList.Web.Common
//Content
//Content
//Content
Page @(Model?.PageCount < Model?.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model,page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }),
new PagedListRenderOptions()
{
ContainerDivClasses = new List<string> {"blog","navigation"},
UlElementClasses = new List<string> {"pagination"},
LiElementClasses = new List<string> {"page-item","page-link"},
ActiveLiElementClass = "active",
})