skip to content

PageModel Handlers

Razor Pages: @page files under Pages, PageModel handlers like OnGet and OnPostAsync, named handlers, [BindProperty] and Post-Redirect-Get with RedirectToPage. Asked when choosing pages over MVC.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In ASP.NET Core Razor Pages, how do the @page directive, the Pages folder and OnGet or OnPost methods route a request to code?

level: juniorimportance: must knowfreq 62%

answer

  1. the file path under /Pages is the URL
  2. Index.cshtml also answers the folder URL
  3. a template after @page appends; "/" replaces
  4. On + verb + optional name + Async
  5. void or Task means Page()

basics

~20 s

A .cshtml file under Pages starting with @page is an endpoint whose URL is its path, with Index also answering the folder URL; a template after @page appends segments. The PageModel method named On plus the HTTP verb, such as OnPostAsync, handles it.

solid answer

~40 s

With `AddRazorPages()` and `app.MapRazorPages()`, every `.cshtml` file under `Pages` that starts with `@page` becomes its own endpoint. Its URL is its path below the root: `Pages/Appointments/Book.cshtml` answers `/Appointments/Book`, and an `Index.cshtml` answers its folder URL as well (`/Appointments`). A string after `@page` appends a route template (`@page "{id:int}"` gives `/Appointments/Details/42`), while one starting with `/` or `~/` replaces the path. The page's `@model` class derives from `PageModel` and holds the handlers: public methods named `On` plus an HTTP verb, optionally a handler name and an `Async` suffix, such as `OnGet`, `OnPostAsync` or `OnPostCancelAsync`. Razor Pages picks the one matching the request's verb (a HEAD request falls back to `OnGet`), binds its parameters and runs it; a handler returning `void` or `Task`, or no handler at all, renders the page as if it returned `Page()`.

code

razor · 8 lines
razor
@page "{id:int}"
@model DetailsModel

<h1>Appointment @Model.Appointment!.Id</h1>
<p>@Model.Appointment.Patient with @Model.Appointment.Dentist</p>
<p>@Model.Appointment.StartsAt.ToString("f")</p>

<a asp-page="./Index">Back to appointments</a>

go deeper

for a junior

Recall that a file's path under Pages is its URL, that Index answers the folder URL, and that OnGet and OnPost handle the matching verbs.

for a middle

Explain appended versus overriding @page templates, the handler naming rule with names and Async, and what a handler's return type means.

for a senior

Diagnose 404s from required route segments, ambiguous-handler exceptions and POSTs that silently render the page because no handler matched.

for a principal

Shape the folder structure of a large Razor Pages app so URLs, areas and conventions stay stable as features are added and moved.

## Pages are endpoints Razor Pages is the page-focused side of ASP.NET Core MVC. Two calls switch it on, `builder.Services.AddRazorPages()` and `app.MapRazorPages()`, and the `dotnet new webapp` template already has both. From then on, every `.cshtml` file under the **root directory** (`/Pages` by default, `RazorPagesOptions.RootDirectory`) whose first directive is `@page` is a routable page. A `.cshtml` file without `@page`, such as a layout or partial, is not an endpoint. A dentist's practice has these pages: | File | `@page` line | Matches | |---|---|---| | `Pages/Index.cshtml` | `@page` | `/` and `/Index` | | `Pages/Appointments/Index.cshtml` | `@page` | `/Appointments` and `/Appointments/Index` | | `Pages/Appointments/Book.cshtml` | `@page` | `/Appointments/Book` | | `Pages/Appointments/Details.cshtml` | `@page "{id:int}"` | `/Appointments/Details/42` | | `Pages/Appointments/Details.cshtml` | `@page "/visit/{id:int}"` | `/visit/42` only | - The page's URL is its path relative to the root, without `.cshtml`. - An `Index.cshtml` answers both its folder URL and the explicit `/Index` form; links generated to it use the folder URL. - A template after `@page` is **appended** to that path. One starting with `/` or `~/` **overrides** it. - Pages in an area live in `Areas/{area}/Pages/...` and get the area name as their first segment. ## The PageModel The `@model` directive names the page's model, a class that derives from `PageModel` and sits next to the file as `Details.cshtml.cs`: ```csharp public class DetailsModel(IAppointmentService appointments) : PageModel { public Appointment? Appointment { get; private set; } public async Task<IActionResult> OnGetAsync(int id) { Appointment = await appointments.FindAsync(id); return Appointment is null ? NotFound() : Page(); } } ``` - Constructor parameters come from dependency injection, as in a controller. - The base class gives `HttpContext`, `Request`, `User`, `ModelState`, `TempData`, `PageContext` and result helpers such as `Page()`, `RedirectToPage()`, `NotFound()` and `Partial()`. - The view reads public properties through `Model`, so `@Model.Appointment.Patient` renders what the handler loaded. ## Page names Every page also has a **page name**: its path below the root without the extension, such as `/Appointments/Details`. Page names, not URLs, are what the rest of Razor Pages speaks: - `asp-page="/Appointments/Details"` and `RedirectToPage("/Appointments/Details", new { id = 42 })` generate the URL from the page's route, so changing the `@page` template never breaks them; - names without a leading `/` are relative to the current page's folder (`./Details`, `../Index`); - conventions such as `Conventions.AddPageRoute("/Appointments/Index", "bookings")` address pages by name. Because links go through page names and routing, moving `Details.cshtml` to another folder changes one name; hard-coded `/Appointments/Details/42` strings would each need editing. ## How a handler is chosen 1. Handler methods are public instance methods whose names start with `On`: `On` + HTTP verb + optional handler name + optional `Async` suffix. `OnGet`, `OnGetAsync`, `OnPost`, `OnPostAsync`, `OnPostCancelAsync` and `OnDelete` all qualify; `[NonHandler]` excludes a method. 2. The request's HTTP method is matched against the verb, case-insensitively. A `HEAD` request with no `OnHead` falls back to the `GET` handlers. 3. If the request carries a handler name (the `handler` route value or query-string key), a handler with that name wins over the unnamed one. 4. Two candidates that remain equally good, such as `OnPost` and `OnPostAsync` on the same page, make Razor Pages throw `InvalidOperationException` for an ambiguous handler at request time. 5. Handler parameters are model-bound (`OnGetAsync(int id)` reads `id` from the route), then the method runs. ## What a handler returns - `void` or `Task`: the page renders, an implicit `Page()`. - `IActionResult` or `Task<IActionResult>`: whatever result you return, such as `Page()`, `RedirectToPage(...)`, `NotFound()` or `Partial("_Slot", slot)`. - If **no** handler matches the verb, the page still renders. A POST to a page that only has `OnGet` is not rejected with 405; once it passes the page's automatic antiforgery check, it renders the page as for a GET. ## The common mistakes Interviewers probe whether a candidate expects a `Controllers` folder, thinks `Index.cshtml` answers only `/Index`, writes both `OnPost` and `OnPostAsync`, or believes a POST without a handler fails. The model to hold is simple: one file, one route, one PageModel, handlers chosen by verb and name.

  • Why does /Appointments/Details without an id return 404 when the page declares @page "{id:int}"?
    The template after `@page` is appended to the page's path, and `{id:int}` is a required segment, so the route only matches URLs that carry an integer there. Without it, no endpoint matches and routing returns 404 before any handler runs. Writing `{id:int?}` makes the segment optional, and `OnGetAsync(int? id)` then has to handle a missing id.
  • What happens if a page declares both OnPost() and OnPostAsync()?
    Both parse to the same verb with no handler name, so they are equally good candidates for every POST. The handler selector throws `InvalidOperationException` for ambiguous handlers when a POST arrives. The `Async` suffix is only a naming convention; keep one of the two.
  • How do you give a page a second URL without moving the file?
    Add a route through the conventions: `builder.Services.AddRazorPages(o => o.Conventions.AddPageRoute("/Appointments/Index", "bookings"))` keeps `/Appointments` and adds `/bookings`. Changing the `@page` line to start with `/` instead replaces the path-based route rather than adding one.

  • Razor Pages need a controller to route requests to each page
  • Pages/Appointments/Index.cshtml only answers the URL /Appointments/Index
  • @page "{id:int}" replaces the folder path with /{id}
  • A POST to a page without OnPost returns 405 Method Not Allowed
  • Declaring both OnPost and OnPostAsync lets the async one win
open as a page

In ASP.NET Core Razor Pages, what does [BindProperty] do on a PageModel property, and why does a GET request need SupportsGet = true?

level: middleimportance: must knowfreq 52%

basics

~20 s

[BindProperty] makes model binding fill a PageModel property before the handler runs, so the handler and the page both use it. Only non-GET requests are bound by default; SupportsGet = true also binds GET, such as a search term.

open as a page

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%

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.

open as a page

In an ASP.NET Core Razor Pages POST handler, when do you return Page() and when RedirectToPage(), and what does each one do?

level: middleimportance: should knowfreq 48%

basics

~20 s

Page() renders the current page in the same request, keeping posted values and ModelState errors, which suits a failed validation; OnGet does not run. RedirectToPage() sends a 302 to a page's URL so the browser issues a GET, which suits success.

open as a page

For a server-rendered ASP.NET Core app, when would you choose Razor Pages over MVC controllers with views, and what do the two share?

level: middleimportance: should knowfreq 44%

basics

~20 s

Choose Razor Pages when the UI is a set of screens, each owning its GET and POST logic; choose MVC controllers when many actions share a controller or mix views and JSON. Both share MVC's binding, validation, tag helpers and layouts.

open as a page

In ASP.NET Core Razor Pages, how do you run code around every page handler with IPageFilter, PageModel overrides or AddRazorPages conventions, and why don't action filters apply?

level: seniorimportance: should knowfreq 27%

basics

~10 s

Implement IPageFilter or IAsyncPageFilter, whose hooks run after handler selection, before the handler and after it, and register it globally, per folder through RazorPagesOptions.Conventions, or on the PageModel. Action filters never run for pages.

open as a page