skip to content

In ASP.NET Core Razor Pages, how do named handlers such as OnPostCancelAsync work, and how does asp-page-handler pick the one a form posts to?

level: middleimportance: should knowfreq 40%

answer

  1. the name between the verb and Async
  2. ?handler=Cancel in the URL
  3. route value or query string, never the form body
  4. @page "{handler?}" moves it into the path
  5. unknown name falls back to OnPost

basics

~20 s

A handler name is the text between the verb and Async: OnPostCancelAsync handles POSTs named Cancel. asp-page-handler="Cancel" on a form or button writes ?handler=Cancel into the URL, and the selector reads that query key or a handler route value.

solid answer

~40 s

Razor Pages parses handler method names as `On` + verb + optional name + optional `Async`, so `OnPostCancelAsync` and `OnPostRescheduleAsync` are POST handlers named `Cancel` and `Reschedule`. `asp-page-handler="Cancel"` on a `<form>`, or on a `<button>` through the form action tag helper, generates a URL carrying `?handler=Cancel`, or a path segment when the page declares `@page "{id:int}/{handler?}"`. The selector reads the name only from the `handler` route value or query-string key, case-insensitively, never from a form field. A named match beats the unnamed handler, but an unknown name removes only the named candidates, so a typo silently runs `OnPostAsync`. Two methods with the same verb and name, `OnPostCancel` plus `OnPostCancelAsync`, throw `InvalidOperationException`. Every `[BindProperty]` property is bound for every POST handler, named ones included.

code

csharp · 15 lines
csharp
public class DetailsModel(IAppointmentService appointments) : PageModel
{
    public async Task<IActionResult> OnPostCancelAsync(int id, string? reason)
    {
        var cancelled = await appointments.CancelAsync(id, reason);
        if (!cancelled) return NotFound();
        return RedirectToPage("./Index");
    }

    public async Task<IActionResult> OnPostRescheduleAsync(int id, DateTime newStart)
    {
        await appointments.MoveAsync(id, newStart);
        return RedirectToPage("./Details", new { id });
    }
}

go deeper

for a junior

Recall that OnPostCancelAsync is the POST handler named Cancel and that asp-page-handler="Cancel" targets it.

for a middle

Explain the naming rule, the ?handler= query key versus a {handler?} route segment, and buttons posting one form to several handlers.

for a senior

Diagnose typos that fall back to OnPostAsync, ambiguous-handler exceptions, and bound properties failing validation on unrelated handlers.

for a principal

Decide when one page with many handlers should split into several pages, keeping each page's inputs and validation coherent.

## One page, several actions A dentist's appointment details page shows one appointment and offers three things to do: confirm it, cancel it, or move it. In MVC these would be three actions; in Razor Pages they are three **handlers** on the same `PageModel`: ```csharp public class DetailsModel(IAppointmentService appointments) : PageModel { public Task<IActionResult> OnPostAsync(int id) => ConfirmAsync(id); public Task<IActionResult> OnPostCancelAsync(int id, string? reason) => CancelAsync(id, reason); public Task<IActionResult> OnPostRescheduleAsync(int id, DateTime newStart) => MoveAsync(id, newStart); // ... } ``` ## How a method name becomes a handler Razor Pages parses each public method that starts with `On`: | Method | Verb | Handler name | |---|---|---| | `OnPost` / `OnPostAsync` | POST | none | | `OnPostCancelAsync` | POST | `Cancel` | | `OnPostReschedule` | POST | `Reschedule` | | `OnGetSlotsAsync` | GET | `Slots` | The `Async` suffix is stripped, so `OnPostCancel` and `OnPostCancelAsync` are the **same** handler; declaring both throws `InvalidOperationException` (ambiguous handler) when a matching request arrives. ## Pointing a form at a handler The tag helpers write the handler name into the URL: ```razor <form method="post" asp-route-id="@Model.Appointment.Id"> <button type="submit">Confirm</button> <button asp-page-handler="Cancel">Cancel</button> <button asp-page-handler="Reschedule">Move</button> </form> ``` - On the `<form>`, `asp-page-handler="Cancel"` makes `action` carry `?handler=Cancel`. - On a `<button>`, the form action tag helper writes a `formaction` with the handler, so one form can post to several handlers. - The same works for links: `<a asp-page-handler="Slots">` targets `OnGetSlotsAsync`. If the query string is unwanted, put the name in the route: `@page "{id:int}/{handler?}"` turns the Cancel button's URL into `/Appointments/Details/42/Cancel`. ## How the selector decides 1. It keeps the handlers whose verb matches the request. 2. It reads the handler name from the **`handler` route value**, or failing that the **`handler` query-string key**. A hidden form field called `handler` is not consulted. 3. It drops the named handlers whose name differs, comparing case-insensitively, but keeps the unnamed ones. 4. A named match scores higher than an unnamed handler; two equal best matches throw `InvalidOperationException`. Step 3 has a consequence worth knowing: with `?handler=Cancle` (a typo), the named `Cancel` handler is dropped but `OnPostAsync` survives, so the **confirm** logic runs. A wrong handler name never produces a 404; it silently reaches the unnamed handler, or renders the page if there is none. ## Binding and validation per handler Handler parameters (`int id`, `string? reason`) are bound only for the handler that declares them. Properties marked `[BindProperty]` are bound for **every** handler whose verb matches. If the page has a `[BindProperty] RescheduleInput Input` with required fields, a click on Cancel binds an empty `Input`, its validation errors land in `ModelState`, and a Cancel handler that checks `ModelState.IsValid` refuses to cancel. Keep handler-specific input in parameters, or validate only what the handler needs. ## Named GET handlers Named handlers are not only for forms. A details page can expose small GET endpoints for scripts on the same page: - `OnGetSlotsAsync(int id, DateOnly day)` answers `/Appointments/Details/42?handler=Slots&day=2026-11-03`; - it can return `new JsonResult(slots)` or `Partial("_Slots", slots)` instead of the whole page; - `<a asp-page-handler="Slots" asp-route-day="2026-11-03">` or a script calling that URL reaches it. This keeps a page's supporting requests next to the page instead of in a separate controller, at the cost of a page model that grows. When a page collects many such handlers, splitting it into several pages, or moving the JSON endpoints to an API, usually reads better. ## What interviewers listen for - The naming rule, including that `Async` does not create a separate handler. - That the handler name travels in the URL (`?handler=` or a `{handler?}` segment). - The fallback to the unnamed handler on an unknown name. - The interaction with `[BindProperty]`, which is the subtle production bug.

  • A Cancel button always fails validation because the page's [BindProperty] Input has required fields. How do you fix it?
    Bound properties are bound and validated for every POST handler, so the Cancel post produces errors for fields it never sends. Move the reschedule fields into the `OnPostRescheduleAsync` parameters (or a parameter object), leaving the Cancel handler with only what it needs, or have the Cancel handler ignore errors that are not its own. The handler named in the URL decides which code runs, not which properties get bound.
  • How do you remove ?handler=Cancel from the URL?
    Declare the handler as a route parameter: `@page "{id:int}/{handler?}"`. The tag helpers then generate `/Appointments/Details/42/Cancel`, and the selector reads the `handler` route value before looking at the query string. Keep the parameter optional so the unnamed handlers still match the plain URL.

  • A hidden input named handler in the form body selects the handler
  • OnPostCancel and OnPostCancelAsync are two different handlers
  • A misspelled handler name makes Razor Pages return 404
  • asp-page-handler needs a separate page file per handler
  • Named handlers bind only their own [BindProperty] properties