Pagination keeps a product catalog from putting every item on one page. An ASP.NET Core controller selects one ordered slice of products for each request; a Razor view displays that slice and provides links to the other pages. section 7.4 section 7.4.1
Build the page in two parts: select the products, then give the view enough information to navigate.
- Give the `Index` action an optional `productPage` parameter defaulting to 1. Order repository products by `ProductID`, skip `(productPage - 1) * PageSize`, and take `PageSize` products. With `PageSize = 4`, a request without a page number shows the first four. section 7.4
- Put the selected products and a `PagingInfo` object in a `ProductsListViewModel`. `PagingInfo` holds `TotalItems`, `ItemsPerPage`, and `CurrentPage`; `TotalPages` rounds the item count divided by the page size upward. section 7.4.1
- Update `Index.cshtml` to render the view model’s `Products`, register the custom tag helper, and add `<div page-model="@Model.PagingInfo" page-action="Index"></div>` to generate page links. section 7.4.1
Listing 7.26 Adding pagination in the HomeController.cs file in the SportsStore/Controllers folder
using Microsoft.AspNetCore.Mvc;
using SportsStore.Models;
namespace SportsStore.Controllers {
public class HomeController : Controller {
private IStoreRepository repository;
public int PageSize = 4;
public HomeController(IStoreRepository repo) {
repository = repo;
}
public ViewResult Index(int productPage = 1)
=> View(repository.Products
.OrderBy(p => p.ProductID)
.Skip((productPage - 1) * PageSize)
.Take(PageSize));
}
}
The controller listing shows the essential ordered `Skip`/`Take` query and the first-page default before navigation data is added. section 7.4
Request and test a page
Request `http://localhost:5000/?productPage=2` to select the second page. For a repeatable check, mock the repository with known products, call `Index(2)`, and assert that the returned products are the expected subset. Test the paging metadata separately: with five products and a page size of three, page 2 should report two total pages. section 7.4 section 7.4.1
Count the same collection you paginate. Once category filtering is added, using the whole repository’s product count can produce links to empty pages within a category. Filter products by the selected category before paging, and set `TotalItems` to that category’s count; use the full count when no category is selected. Test both cases with known category data. section 8.1.4










