Skip to content

9.7 — Razor Pages and PageModel

← Roadmap · Section: 9. MVC, Razor Pages and Views Prev: 9.6 ViewData, ViewBag and TempData · Next: 9.8 ViewModels

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Razor Pages organises server-rendered code by page rather than by controller. Each URL is one .cshtml file plus a PageModel class beside it.

  • Handlers are named by convention: OnGet, OnPost, OnPostDeleteAsync.
  • Routing is folder-based — Pages/Orders/Details.cshtml serves /Orders/Details.
  • It is MVC underneath — same model binding, filters, DI and validation. Just a different organisation.

Definitions

Term What it is What it means
Razor Page a .cshtml file with @page A self-contained page. Its own URL, model and handlers.
@page a directive Makes the file a Razor Page rather than a view. Must be the first line.
PageModel an abstract class The code-behind. Holds handlers, bound properties and page data.
Code-behind the .cshtml.cs file The PageModel class beside the page. Nested in Solution Explorer.
Handler a method like OnGet Handles one HTTP method. Found by naming convention.
Named handler OnPostDelete An extra handler for the same method, selected by ?handler=Delete.
[BindProperty] an attribute Binds a property from the request. SupportsGet for GET requests.
asp-page a tag helper attribute Links to a page by path.
asp-page-handler a tag helper attribute Targets a named handler.
Page() a method Returns a PageResult — renders this page. Like View().
RedirectToPage() a method Redirects to another page.

The concept

Organised by page, not by controller

MVC groups by controller: one OrdersController with Index, Details, Create and Edit actions, and their views in Views/Orders/. Changing the Create page means editing the controller (shared with everything else) and its view.

Razor Pages groups by page:

Pages/
└── Orders/
    ├── Index.cshtml          + Index.cshtml.cs
    ├── Details.cshtml        + Details.cshtml.cs
    └── Create.cshtml         + Create.cshtml.cs

Everything about the Create page is in two files that sit together. Changing it touches nothing else.

A picture: a filing cabinet organised by customer rather than by document type. MVC keeps all the invoices together and all the contracts together; Razor Pages keeps everything about one customer in one folder. Which is better depends on whether you more often work across documents or within a customer.

It is MVC underneath

Worth being clear about: Razor Pages is not a different framework. It uses the same model binding, the same filters, the same dependency injection, the same validation and the same tag helpers.

The difference is organisational — and the routing, which is folder-based rather than attribute- or convention-driven.

When to choose it

Razor Pages suits a site where each URL is one page with one or two actions — a form, a list, a details screen. Most server-rendered CRUD applications are exactly that shape.

MVC suits cases where several actions share setup, or where the same controller serves several representations. And APIs are always MVC or minimal APIs — Razor Pages is for HTML.

⚠️ Microsoft's own guidance recommends Razor Pages for new page-based apps. The reason is that MVC controllers in a page-based site tend to grow into unrelated actions sharing a class for no reason other than the noun in their name.


How it works

The simple version

@* Pages/Orders/Details.cshtml *@
@page "{id:guid}"
@model MyApp.Pages.Orders.DetailsModel
@{
    ViewData["Title"] = $"Order {Model.Order.Reference}";
}

<h1>Order @Model.Order.Reference</h1>
<p>Placed @Model.Order.CreatedAt.ToString("d MMMM yyyy")</p>

@if (Model.Order.CanCancel)
{
    <form method="post" asp-page-handler="Cancel">
        <button type="submit" class="btn btn-danger">Cancel this order</button>
    </form>
}
// Pages/Orders/Details.cshtml.cs
public class DetailsModel(IOrderService orders) : PageModel
{
    public OrderDetailsViewModel Order { get; private set; } = default!;

    // GET /Orders/Details/{id}
    public async Task<IActionResult> OnGetAsync(Guid id, CancellationToken ct)
    {
        var order = await orders.GetAsync(id, ct);
        if (order is null) return NotFound();

        Order = OrderDetailsViewModel.From(order);
        return Page();                                  // renders this page
    }

    // POST /Orders/Details/{id}?handler=Cancel
    public async Task<IActionResult> OnPostCancelAsync(Guid id, CancellationToken ct)
    {
        var result = await orders.CancelAsync(id, ct);

        TempData[result.IsSuccess ? "Success" : "Error"] =
            result.IsSuccess ? "Order cancelled." : result.Reason;

        return RedirectToPage(new { id });              // PRG — see 9.6
    }
}

⚠️ @page must be the first directive in the file. Anything before it and the file is treated as an ordinary view, so the URL 404s with no obvious explanation.

Routing is folder-based

File URL
Pages/Index.cshtml /
Pages/Orders/Index.cshtml /Orders
Pages/Orders/Details.cshtml /Orders/Details
Pages/Orders/Details.cshtml with @page "{id:guid}" /Orders/Details/{id}

Index.cshtml maps to the folder itself, so /Orders and /Orders/Index both work.

The route template after @page is appended, not replacing:

@page "{id:guid}"           @* /Orders/Details/{id} *@
@page "{id:guid?}"          @* optional — /Orders/Details works too *@
@page "/custom/path"        @* a leading slash REPLACES the folder route *@

Route templates, constraints and precedence work exactly as in 8.4 and 8.5.

Handler naming

Handlers are found by convention:

Method Handler URL
GET OnGet / OnGetAsync the page URL
POST OnPost / OnPostAsync the page URL
POST OnPostDeleteAsync ?handler=Delete
GET OnGetExportAsync ?handler=Export

Named handlers let one page have several actions:

public async Task<IActionResult> OnPostApproveAsync(Guid id, CancellationToken ct) { }
public async Task<IActionResult> OnPostRejectAsync(Guid id, CancellationToken ct) { }
<form method="post" asp-page-handler="Approve">
    <button type="submit">Approve</button>
</form>
<form method="post" asp-page-handler="Reject">
    <button type="submit">Reject</button>
</form>

⚠️ The Async suffix is stripped when matching. OnPostDeleteAsync is reached with ?handler=Delete, not ?handler=DeleteAsync. Using the full name silently fails to match and falls back to OnPost, or 404s.

⚠️ [BindProperty] and the GET trap

[BindProperty] binds a property from the request instead of using a method parameter:

public class CreateModel(IOrderService orders) : PageModel
{
    [BindProperty]
    public CreateOrderInput Input { get; set; } = new();

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        if (!ModelState.IsValid) return Page();         // redisplay with errors

        await orders.CreateAsync(Input.ToRequest(), ct);

        TempData["Success"] = "Order created.";
        return RedirectToPage("./Index");
    }
}
@page
@model CreateModel

<form method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <label asp-for="Input.CustomerName"></label>
    <input asp-for="Input.CustomerName" class="form-control" />
    <span asp-validation-for="Input.CustomerName" class="text-danger"></span>

    <button type="submit">Create</button>
</form>

⚠️ [BindProperty] does not bind on GET by default. That is deliberate — binding query strings into page state on GET invites tampering. If you genuinely need it:

[BindProperty(SupportsGet = true)]
public string? SearchTerm { get; set; }

Use that sparingly, and never for anything that changes state.

⚠️ [BindProperty] binds the whole object, so it has the same over-posting risk as MVC — a malicious form field maps onto a property you did not intend to expose. Bind to a purpose-built input model, not an entity (11.10).

How it actually works — the comparison

MVC Razor Pages
Organised by Controller Page
Routing Attributes or conventions Folder structure
Code location Controller + Views/ folder Two files side by side
Handler naming Any method name OnGet, OnPost convention
Model binding Parameters or [FromBody] Parameters or [BindProperty]
Filters Action filters Page filters (IPageFilter)
Suits Multiple actions per resource; APIs One page, one URL

⚠️ Filters differ. Razor Pages uses IPageFilter and IAsyncPageFilter rather than action filters, so an existing IActionFilter does not apply to pages. Authorization filters and result filters do work across both (12.1).

Authorization conventions

A genuinely useful feature — securing whole folders at once:

builder.Services.AddRazorPages(options =>
{
    options.Conventions.AuthorizeFolder("/Admin", policy: "AdminOnly");
    options.Conventions.AuthorizePage("/Account/Manage");
    options.Conventions.AllowAnonymousToPage("/Admin/Login");
});

That is better than an attribute per page, because a new page added to /Admin is protected automatically — you cannot forget. Forgetting an [Authorize] on a new admin page is a real security hole, and this removes the possibility (16.8).

The deeper detail — mixing with MVC and APIs

They coexist in one application:

builder.Services.AddRazorPages();
builder.Services.AddControllers();        // for the API

var app = builder.Build();

app.MapRazorPages();
app.MapControllers();

A common and sensible shape: Razor Pages for the site's HTML, API controllers or minimal APIs for JSON endpoints. They share the host, the DI container, the middleware pipeline and authentication.

⚠️ MapRazorPages() is required. Registering the services with AddRazorPages() and forgetting to map them means every page 404s, with no error explaining why — the same shape of mistake as AddControllers without MapControllers.


Code

A complete list-and-create pair:

// Pages/Orders/Index.cshtml.cs
public class IndexModel(IOrderService orders) : PageModel
{
    public IReadOnlyList<OrderSummaryViewModel> Orders { get; private set; } = [];

    [BindProperty(SupportsGet = true)]
    public string? Search { get; set; }

    [BindProperty(SupportsGet = true)]
    public int PageNumber { get; set; } = 1;

    public async Task OnGetAsync(CancellationToken ct)
    {
        Orders = await orders.SearchAsync(Search, PageNumber, ct);
    }

    // POST /Orders?handler=Delete
    public async Task<IActionResult> OnPostDeleteAsync(Guid id, CancellationToken ct)
    {
        var result = await orders.DeleteAsync(id, ct);

        TempData[result.IsSuccess ? "Success" : "Error"] =
            result.IsSuccess ? "Order deleted." : result.Reason;

        return RedirectToPage();          // PRG — refresh is safe
    }
}
@page
@model MyApp.Pages.Orders.IndexModel
@{
    ViewData["Title"] = "Orders";
}

<h1>Orders</h1>

@* GET form for search — no antiforgery token needed, it changes nothing *@
<form method="get">
    <input asp-for="Search" class="form-control" placeholder="Search orders" />
    <button type="submit">Search</button>
</form>

<table class="table">
    <tbody>
    @foreach (var order in Model.Orders)
    {
        <tr>
            <td><a asp-page="./Details" asp-route-id="@order.Id">@order.Reference</a></td>
            <td>@order.Total.ToString("C")</td>
            <td>
                @* POST form — gets an antiforgery token automatically. See 17.4. *@
                <form method="post" asp-page-handler="Delete" asp-route-id="@order.Id">
                    <button type="submit" class="btn btn-sm btn-danger">Delete</button>
                </form>
            </td>
        </tr>
    }
    </tbody>
</table>

<a asp-page="./Create" class="btn btn-primary">New order</a>

Three details worth explaining:

asp-page="./Details" is a relative page path. The leading ./ keeps it relative to the current folder, so moving the folder does not break the link.

The search form is method="get" — it does not change state, so it needs no antiforgery token and the URL stays shareable and bookmarkable.

The delete form is method="post" with a named handler, and gets an antiforgery token automatically from the tag helpers (9.5).


Interview questions

Q: What are Razor Pages and how do they differ from MVC?

Razor Pages organises server-rendered code by page rather than by controller — each URL is a .cshtml file with a PageModel class beside it, and routing comes from the folder structure rather than attributes or conventions. Handlers are named by convention: OnGet, OnPost, and named variants like OnPostDeleteAsync reached with a handler query parameter. Underneath it is the same framework — same model binding, filters, DI and validation — so the difference is organisational rather than technical.

Q: When would you choose Razor Pages over MVC?

For a page-based site where each URL is essentially one screen with one or two actions, which describes most server-rendered CRUD applications. Everything about a page lives in two files that sit together, so changing it touches nothing shared. MVC suits cases where several actions share setup or one controller serves several representations, and APIs are always MVC or minimal APIs since Razor Pages is for HTML. Microsoft's own guidance recommends Razor Pages for new page-based apps, largely because MVC controllers in that shape tend to accumulate unrelated actions.

Q: How does [BindProperty] work, and what is the catch?

It binds a property on the PageModel from the request rather than taking a method parameter, which is how forms usually post into a page. The catch is that it does not bind on GET by default — that is deliberate, since binding query strings into page state on GET invites tampering — so you need SupportsGet = true for something like a search term, and you should never use it for anything that changes state. It also binds the whole object, so it has the same over-posting risk as MVC and should target a purpose-built input model rather than an entity.

Q: What is a useful Razor Pages feature that MVC lacks?

Authorization conventions. options.Conventions.AuthorizeFolder("/Admin", "AdminOnly") applies a policy to every page in a folder in one line, so a new page added there is protected automatically. That removes a real security failure mode — someone adding an admin page and forgetting the [Authorize] attribute. There are matching conventions for authorizing a single page and for allowing anonymous access to one, such as the login page inside a protected folder.


Traps ⚠️

  • @page must be the first directive. Otherwise the file is a view and the URL 404s with no explanation.
  • The Async suffix is stripped when matching handlers. OnPostDeleteAsync is ?handler=Delete.
  • [BindProperty] does not bind on GET without SupportsGet = true.
  • [BindProperty] binds the whole object — the same over-posting risk as MVC.
  • AddRazorPages() without MapRazorPages() means every page 404s.
  • Action filters do not apply to pages. Razor Pages uses IPageFilter.
  • A leading / in @page replaces the folder route rather than appending to it.
  • Page file names are case-sensitive on Linux, like views (9.4).
  • Returning Page() after a successful POST re-submits on refresh. Redirect instead.


Sources