IC Improve Code Recipes

Recipe 16.4 · C#

A Reusable Paging Model for Grids

Problem

Grids page through data in almost every screen. The Web Forms version loads every row into a DataSet, binds it to a GridView with AllowPaging="true", and lets the control throw away all but 25 rows. On a table with 400,000 rows that's slow for the user and expensive for the database, and the pager code is copied into every screen.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: load everything, page in memory.
protected void BindGrid()
{
    DataSet ds = SqlHelper.ExecuteDataset(ConnString,
        CommandType.Text, "SELECT * FROM Invoice");
    gvInvoices.DataSource = ds;
    gvInvoices.DataBind();
}

protected void gvInvoices_PageIndexChanging(object sender,
    GridViewPageEventArgs e)
{
    gvInvoices.PageIndex = e.NewPageIndex;
    BindGrid();                       // runs the query again
}

The improved recipe

C#
using System;
using System.Collections.Generic;
using System.Linq;

namespace ImproveCode.Web.Paging;

public sealed record PageRequest
{
    public const int DefaultPageSize = 25;
    public const int MaxPageSize = 200;

    public PageRequest(int page, int pageSize = DefaultPageSize)
    {
        Page = Math.Clamp(page, 1, int.MaxValue / MaxPageSize);
        PageSize = Math.Clamp(pageSize, 1, MaxPageSize);
    }

    public int Page { get; }
    public int PageSize { get; }
    public int Skip => (Page - 1) * PageSize;
}

public interface IPagedResult
{
    int Page { get; }
    int TotalCount { get; }
    int TotalPages { get; }
    bool HasPrevious { get; }
    bool HasNext { get; }
    int FirstItem { get; }
    int LastItem { get; }
    IReadOnlyList<int?> PageNumbers(int window = 7);
}

public sealed class PagedResult<T>(
    IReadOnlyList<T> items, int totalCount, PageRequest request)
    : IPagedResult
{
    public IReadOnlyList<T> Items { get; } = items;
    public int TotalCount { get; } = Math.Max(0, totalCount);
    public int Page { get; } = request.Page;
    public int PageSize { get; } = request.PageSize;

    public int TotalPages =>
        (int)((TotalCount + (long)PageSize - 1) / PageSize);

    public bool HasPrevious => Page > 1;
    public bool HasNext => Page < TotalPages;

    public int FirstItem =>
        Items.Count == 0 ? 0 : ((Page - 1) * PageSize) + 1;

    public int LastItem =>
        Items.Count == 0 ? 0 : FirstItem + Items.Count - 1;

    public IReadOnlyList<int?> PageNumbers(int window = 7) =>
        PageWindow.Compute(Page, TotalPages, window);
}

public static class PageWindow
{
    // Page numbers to show; null marks a gap ("...").
    public static IReadOnlyList<int?> Compute(
        int current, int totalPages, int window = 7)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(window, 5);
        var pages = new List<int?>(window);
        if (totalPages <= window)
        {
            for (int i = 1; i <= totalPages; i++)
            {
                pages.Add(i);
            }
            return pages;
        }

        current = Math.Clamp(current, 1, totalPages);
        int inner = window - 2;
        int start = Math.Max(2, current - (inner / 2));
        int end = start + inner - 1;
        if (end > totalPages - 1)
        {
            end = totalPages - 1;
            start = end - inner + 1;
        }

        pages.Add(1);
        if (start > 2)
        {
            pages.Add(null);
            start++;
        }

        bool gapAtEnd = end < totalPages - 1;
        if (gapAtEnd)
        {
            end--;
        }

        for (int i = start; i <= end; i++)
        {
            pages.Add(i);
        }

        if (gapAtEnd)
        {
            pages.Add(null);
        }

        pages.Add(totalPages);
        return pages;
    }
}

public static class PagingExtensions
{
    // The query must be ordered before paging.
    public static PagedResult<T> ToPagedResult<T>(
        this IQueryable<T> query, PageRequest request)
    {
        int total = query.Count();
        List<T> items = query
            .Skip(request.Skip)
            .Take(request.PageSize)
            .ToList();
        return new PagedResult<T>(items, total, request);
    }
}

Links keep the other query-string values (filters, sort) and replace only the page:

C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;

namespace ImproveCode.Web.Paging;

public static class PageLinks
{
    public static string Url(HttpRequest request, int page)
    {
        IEnumerable<KeyValuePair<string, string?>> query =
            request.Query
                .Where(q => !q.Key.Equals(
                    "page", StringComparison.OrdinalIgnoreCase))
                .SelectMany(q => q.Value.Select(
                    v => new KeyValuePair<string, string?>(q.Key, v)))
                .Append(new("page",
                    page.ToString(CultureInfo.InvariantCulture)));

        string path = (request.PathBase + request.Path).ToString();
        return QueryHelpers.AddQueryString(path, query);
    }
}

The controller asks a query service for one page:

C#
using System;
using System.Threading;
using System.Threading.Tasks;
using ImproveCode.Web.Filters;
using ImproveCode.Web.Paging;
using ImproveCode.Web.Session;
using Microsoft.AspNetCore.Mvc;

namespace ImproveCode.Web.Controllers;

public sealed record InvoiceRow(
    int InvoiceId, string InvoiceNumber, DateOnly InvoiceDate,
    decimal Total);

public interface IInvoiceQueries
{
    Task<PagedResult<InvoiceRow>> SearchAsync(
        int customerId, PageRequest page, CancellationToken ct);
}

public sealed class InvoicesController(
    IInvoiceQueries invoices, IUserSession userSession)
    : AppController
{
    [RequirePermission("Invoices.View")]
    public async Task<IActionResult> Index(
        int page = 1,
        int size = PageRequest.DefaultPageSize,
        CancellationToken ct = default)
    {
        if (userSession.SelectedCustomerId is not int customerId)
        {
            return RedirectToAction("Select", "Customers");
        }

        PagedResult<InvoiceRow> result = await invoices.SearchAsync(
            customerId, new PageRequest(page, size), ct);
        return View(result);
    }
}

The query behind SearchAsync uses OFFSET/FETCH (Chapter 2):

SQL
SELECT COUNT(*) FROM dbo.Invoice WHERE CustomerId = @CustomerId;

SELECT InvoiceId, InvoiceNumber, InvoiceDate, Total
FROM dbo.Invoice
WHERE CustomerId = @CustomerId
ORDER BY InvoiceDate DESC, InvoiceId DESC
OFFSET @Skip ROWS FETCH NEXT @PageSize ROWS ONLY;

And one partial view renders the pager for every grid:

Text
@* Views/Shared/_Pager.cshtml *@
@using ImproveCode.Web.Paging
@model IPagedResult

@if (Model.TotalPages > 1)
{
    <nav aria-label="Pages">
        <ul class="pagination">
            @if (Model.HasPrevious)
            {
                <li class="page-item">
                    <a class="page-link" href="@PageLinks.Url(
                        Context.Request, Model.Page - 1)">Previous</a>
                </li>
            }
            @foreach (int? number in Model.PageNumbers())
            {
                if (number is int n)
                {
                    <li class="page-item @(n == Model.Page
                        ? "active" : "")">
                        <a class="page-link" href="@PageLinks.Url(
                            Context.Request, n)">@n</a>
                    </li>
                }
                else
                {
                    <li class="page-item disabled">
                        <span class="page-link">&hellip;</span>
                    </li>
                }
            }
            @if (Model.HasNext)
            {
                <li class="page-item">
                    <a class="page-link" href="@PageLinks.Url(
                        Context.Request, Model.Page + 1)">Next</a>
                </li>
            }
        </ul>
    </nav>
    <p>Showing @Model.FirstItem to @Model.LastItem
        of @Model.TotalCount</p>
}

In any grid view: @await Html.PartialAsync("_Pager", Model).

How it works

PageRequest cleans up input once. A page of 0, -3 or 999999999 and a page size of 100000 from a hand-edited URL are clamped to safe values, so a user can't ask the database for a million rows. Skip is computed in one place, which is where off-by-one errors used to hide.

PagedResult<T> carries one page of items plus the numbers the pager needs. TotalPages uses long arithmetic, so a large total doesn't overflow. FirstItem and LastItem produce "Showing 26 to 50 of 1,203" without anyone doing arithmetic in a view.

PageWindow.Compute produces a fixed-width list such as 1 … 9 10 11 … 20: always the first and last page, the current page with neighbors, and null where a gap goes. The pager's width doesn't jump as the user clicks, and the logic is a pure function you can unit test.

The database does the paging. The archive shows how rare that has been: about 692 SQL files page with ROW_NUMBER() OVER (10 engagements), and only 5 files in 1 engagement use OFFSET ... FETCH. Most grids paged in memory. The two queries above return 25 rows and one count, and an index on (CustomerId, InvoiceDate DESC, InvoiceId DESC) makes both cheap.

ToPagedResult covers IQueryable sources, including LINQ to Objects and Entity Framework Core. The partial view works for any PagedResult<T> through the non-generic IPagedResult interface.

Variations and pitfalls

  • Always order by a unique key as the last column. Without a deterministic order, rows can appear on two pages or on none.
  • With EF Core, write an async twin of ToPagedResult using CountAsync and ToListAsync from Microsoft.EntityFrameworkCore.
  • OFFSET gets slower on deep pages because SQL Server still reads the skipped rows. For "infinite scroll" or exports, use keyset paging: WHERE (InvoiceDate, InvoiceId) < (@LastDate, @LastId), expressed as InvoiceDate < @LastDate OR (InvoiceDate = @LastDate AND InvoiceId < @LastId).
  • If the count is expensive on huge tables, cache it briefly or show "more than 10,000" instead of an exact number.
  • When the requested page is past the end (records were deleted), the result has no items. Show a link back to page 1, or redirect to the last page.