ASP.NET Core 2.2 - Bootstrap 4 Pagination
This article will demonstrate the use of Bootstrap 4 pagination for a table of entities. I will assume you have created a new ASP.NET Core 2.2 Razor Pages project. I won't use Identity or Individual User Accounts.
This article continues a series about table functions:
The FREE ASP.NET Core 6.0 - Demos And Utilities Project includes a Table Functions Demo. Access to the source code is free for registered users at Manage > Assets.
I used instructions from Simple Paging In ASP.NET Core Razor Pages by Mike Brind with a couple of modifications.
Edit Index.cshtml.cs, add the paging properties:
private readonly FoodDbContext _context;
public IndexModel(FoodDbContext context)
{
_context = context;
}
public int CurrentPage { get; set; } = 1;
public int Count { get; set; }
public int PageSize { get; set; } = 10;
public int TotalPages => (int)Math.Ceiling(decimal.Divide(Count, PageSize));
public bool EnablePrevious => CurrentPage > 1;
public bool EnableNext => CurrentPage < TotalPages;
public IList<Food> Foods { get; set; } = new List<Food>();
public void OnGet(int currentPage)
{
CurrentPage = currentPage == 0 ? 1 : currentPage;
Count = _context.Foods.Count();
if (CurrentPage > TotalPages)
CurrentPage = TotalPages;
Foods = _context.Foods
.Skip((CurrentPage - 1) * PageSize)
.Take(PageSize)
.ToList();
}
Edit Index.cshtml, add the paging elements:
<nav aria-label="Page navigation">
<ul class="pagination flex-wrap">
<li class="page-item @(Model.EnablePrevious ? " " : " disabled" )">
<a asp-route-currentPage="1"
class="page-link" aria-label="Frist">
<span aria-hidden="true">|<</span>
<span class="sr-only">First</span>
</a>
</li>
<li class="page-item @(Model.EnablePrevious ? " " : " disabled" )">
<a asp-route-currentPage="@(Model.CurrentPage -1)"
class="page-link" aria-label="Next">
<span aria-hidden="true"><</span>
<span class="sr-only">Next</span>
</a>
</li>
@for (var i = 1; i <= Model.TotalPages; i++)
{
<li class="page-item @(i == Model.CurrentPage ? "active" : "")">
<a asp-route-currentPage="@i" class="page-link">@i</a>
</li>
}
<li class="page-item @(Model.EnableNext ? " " : " disabled" )">
<a asp-route-currentpage="@(Model.CurrentPage + 1)"
class="page-link" aria-label="Previous">
<span aria-hidden="true">></span>
<span class="sr-only">Previous</span>
</a>
</li>
<li class="page-item @(Model.EnableNext ? " " : " disabled" )">
<a asp-route-currentPage="@Model.TotalPages"
class="page-link" aria-label="Last">
<span aria-hidden="true">>|</span>
<span class="sr-only">Last</span>
</a>
</li>
</ul>
</nav>
Notice the flex-wrap class for the ul element. This will wrap the page number list as needed.
Update 12/30/2021
Announced the ASP.NET Core 6.0 - Demos And Utilities Project. Updated articles, asset and topic links.
Comments(0)