Skip to content
Tutorials Center
My learning

Topics

Lesson 141 of 182 ยท ASP.NET Core

MVC, Razor Pages and Blazor

Compare ASP.NET Core MVC, Razor Pages, Blazor and minimal APIs - controllers, views, Razor syntax, tag helpers, model binding and validation, and how to choose, with runnable C# controller demos.

ASP.NET Core offers several ways to build the user-facing side of a web application. You have already met minimal APIs, which are ideal for JSON endpoints. For pages that return HTML, forms and interactive screens, the framework adds three more programming models: MVC (controllers and views), Razor Pages (a page with its own handler code), and Blazor (components written in C# that can run on the server or in the browser). All of them sit on the same foundations: the middleware pipeline, routing, model binding, validation, dependency injection and authentication. Choosing between them is mostly a question of how your team likes to organize code, and how interactive the UI must be.

This lesson explains each model, teaches Razor syntax (the mix of HTML and C# that powers MVC views, Razor Pages and Blazor), and demonstrates the parts that can run in our environment: controllers, conventional and attribute routing, model binding, ModelState, the post-redirect-get pattern and HTML encoding. Razor files themselves (.cshtml, .razor) are compiled to C# by the SDK at build time, and our single-file runner has no build step, so Razor markup is shown read-only and clearly labeled.

Runnable examples use Kestrel on loopback and HttpClient, as in the earlier lessons. In a real project the using lines are implicit, and views live in .cshtml files under Views/. Here, controller actions return HTML as strings, so you can run the full request cycle in one file.

The four models at a glance

Model Unit of code Best for Interactivity
Minimal APIs A lambda or method per endpoint JSON APIs, microservices, small apps None built in (backend only)
MVC Controller + action methods + views Larger apps, HTML plus JSON from one codebase, teams that like separation Page loads and forms; JavaScript on top
Razor Pages A page: .cshtml template + PageModel class Page-focused sites: forms, dashboards, admin screens Page loads and forms; JavaScript on top
Blazor Components (.razor) with C# markup and events Rich interactive UIs written in C# instead of JavaScript Full: events, two-way binding, live updates

They can be mixed in one application. A common setup: Razor Pages or Blazor for the site, minimal APIs or controllers for the JSON API used by a mobile app, all in one project sharing services and authentication.

MVC: models, views and controllers

Model-View-Controller splits a page into three responsibilities:

  • The controller receives the request, calls your services and chooses the response.
  • The model is the data the view needs (a view model, usually a plain class or record) plus your domain logic.
  • The view turns the model into HTML.

A controller is a class (usually named SomethingController, deriving from Controller for pages or ControllerBase for APIs). Each public method is an action. The URL reaches an action through routing, either by convention (/{action}/{id?}) or with attributes ([HttpGet("products/{id}")]). Actions return an IActionResult: View(model), Content(...), Json(...), Redirect..., NotFound(), BadRequest(), File(...) and so on.

The next program is a small MVC application with conventional routing. Two controllers produce HTML pages. A tiny static Views class plays the role of .cshtml files; you will see the real Razor equivalent below. Note the important detail in Views.Details: every value that comes from the user is HTML-encoded.

C# Controllers with conventional routing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

GET / reached HomeController.Index through the defaults in the route pattern; /Products reached ProductsController.Index; /Products/Details/2 bound id from the route to the int parameter. The hostile third product shows &lt;script&gt; in both the title and the heading, never a live <script> tag. A missing product returns NotFound(), a bare 404.

Notice that ProductsController receives ProductCatalog through its constructor. Controllers are created by the dependency injection container for each request, so any registered service can be injected (see Dependency Injection). Keep controllers thin: bind input, call a service, choose a result. Business rules belong in services you can test without HTTP.

What a real Razor view looks like

In a real MVC project, Views.Details would be a file Views/Products/Details.cshtml, and the action would end with return View(product);. Razor files mix HTML with C#, where @ switches from markup to code:

HTML
@* Views/Products/Details.cshtml  (read-only: needs the Razor compiler of a real project) *@
@model Product
@{
    ViewData["Title"] = Model.Name;
}

<h1>@Model.Name</h1>
<p>Price: @Model.Price.ToString("C")</p>

@if (Model.Price > 40)
{
    <p class="badge">Premium</p>
}

<ul>
    @foreach (var tag in Model.Tags)
    {
        <li>@tag</li>
    }
</ul>

The rules of Razor syntax are few and consistent:

  • @expression writes a value, HTML-encoded by default. @Model.Name is safe even if the name contains <script>.
  • @(a + b) is an explicit expression for anything with spaces or operators.
  • @{ ... } is a code block; @if, @foreach, @for, @switch, @using start statements, and the braces contain markup again.
  • @* comment *@ is a Razor comment that never reaches the browser.
  • @@ is a literal @; email addresses in text are recognized and left alone.
  • @Html.Raw(x) writes x without encoding. Use it only for markup you generated and trust.
  • Directives: @model (the view model type), @using, @inject (a service), @functions, @section.

A layout (_Layout.cshtml) holds the shared page frame (header, navigation, scripts) and calls @RenderBody() where each page's content goes. _ViewStart.cshtml selects the layout, and _ViewImports.cshtml adds @using lines and tag helpers for the whole folder. Partial views (<partial name="_ProductCard" model="p" />) are reusable fragments, and view components are reusable pieces with their own logic (a shopping-cart badge, a menu).

Razor encodes by default: seeing it in plain C#

Razor does not run at runtime in our sandbox, but the idea behind it is simple, and you can reproduce it with the same encoder classes it uses. A .cshtml file is translated into a C# class that calls two methods in sequence: write a literal chunk of HTML as-is, and write an expression after encoding. The program below does by hand what the compiler generates for a tiny template:

HTML
<p>Hello, @Model.Name! You have @Model.Count new messages.</p>
C# What Razor generates: literals and encoded expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The name came out as &lt;b&gt;Eve&lt;/b&gt; &amp; co, so the browser shows the characters literally instead of interpreting them; the footer, an IHtmlContent, was written as markup. This is the whole security model of Razor in one picture, and it is why Html.Raw and HtmlString deserve scrutiny in code review: they are the places where cross-site scripting (XSS) can slip in. (The encoder also turns quotes into &quot;, which keeps attribute values safe.)

Tag helpers

Tag helpers let server-side C# take part in HTML elements while keeping the markup readable. Instead of generating URLs with helper method calls, you add attributes to ordinary tags:

HTML
<!-- Read-only: Razor with tag helpers -->
<a asp-controller="Products" asp-action="Details" asp-route-id="@p.Id">@p.Name</a>
<!-- renders: <a href="/Products/Details/2">Mouse</a> -->

<form asp-action="Signup" method="post">
    <label asp-for="Name"></label>
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>
    <button type="submit">Join</button>
</form>
<!-- the form tag helper also adds the antiforgery token -->

asp-for binds a field to a model property: it fills the id, name and value attributes, adds HTML5 validation attributes from your DataAnnotations, and repopulates the field when the form redisplays after an error. asp-controller/asp-action/asp-route-* build URLs from your routing configuration, so renaming a route does not leave dead links. Tag helpers are enabled by @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers in _ViewImports.cshtml.

Model binding, ModelState and post-redirect-get

When a form is submitted, the framework binds the posted fields to your action's parameters and validates the result with DataAnnotations. The outcome lands in ModelState. The standard pattern for form handling is:

  1. GET /signup shows an empty form.
  2. POST /signup: if ModelState.IsValid is false, redisplay the same form with the entered values and the error messages (status 200; the user fixes the fields).
  3. If it is valid, do the work and redirect (status 302/303) to a GET page such as a confirmation. This is post-redirect-get (PRG). It prevents the browser's "resubmit the form?" warning and duplicate orders when a user refreshes.
C# Form posting, ModelState and post-redirect-get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The invalid post is answered with 200 and a list of messages (a real view would show them next to the fields). The valid post is answered with 302 and a Location pointing at the confirmation page; the browser then issues a harmless GET. In a real MVC form you would also add [ValidateAntiForgeryToken] (or [AutoValidateAntiforgeryToken] globally) and the form tag helper, which embeds the matching token, to defend against cross-site request forgery.

Over-posting. If you bind straight to an entity with an IsAdmin property, a malicious client can add IsAdmin=true to the form. Bind to a dedicated view model or input class that contains only the fields the form should set, as SignupForm does here.

Controllers for APIs: [ApiController]

Putting [ApiController] on a controller switches on API-friendly behavior: attribute routing is required, parameters are bound from the right sources by inference (complex types from the body), and invalid models are rejected automatically with a 400 problem details response before your action runs. That is the validation behavior the previous lesson implemented by hand for minimal APIs.

C# An [ApiController] with automatic validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The invalid body never reached Create: the framework answered 400 with a problem details document listing every failing field. /api/books/abc does not match the {id:int} constraint, so routing finds no endpoint and returns 404. ActionResult<Book> lets an action return either a Book (serialized as 200) or any status result, and it gives OpenAPI generators the response type.

Minimal APIs and controllers overlap almost completely for JSON. Minimal APIs have less ceremony and start faster; controllers offer filters, model-binding extensibility, conventions and a long-established structure for big teams. Both are fully supported.

Razor Pages

Razor Pages puts the view and its logic together, organized by page instead of by controller. A page is a .cshtml file with an @page directive; its code lives in a PageModel class (usually in the code-behind file Signup.cshtml.cs). The URL comes from the file path: Pages/Signup.cshtml is /Signup. Handlers are methods named OnGet, OnPost, OnPostDelete and so on.

C#
// Read-only: Pages/Signup.cshtml.cs  (requires builder.Services.AddRazorPages() and app.MapRazorPages())
public class SignupModel : PageModel
{
    [BindProperty]                                   // bound from the posted form
    public SignupForm Form { get; set; } = new();

    public void OnGet() { }                          // GET /Signup shows the empty form

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();                           // redisplay with errors
        }
        // ...save...
        return RedirectToPage("Done", new { name = Form.Name });
    }
}
HTML
@* Pages/Signup.cshtml *@
@page
@model SignupModel

<form method="post">
    <input asp-for="Form.Name" />
    <span asp-validation-for="Form.Name"></span>
    <button>Join</button>
</form>

Everything you learned about model binding, ModelState and PRG applies unchanged. Razor Pages is usually the simplest way to build page-oriented sites: related markup and code sit side by side, there is no controller/views folder jumping, and each page has a clear URL. MVC shines when one controller serves many views and you also expose APIs from the same classes.

Blazor: components in C#

Blazor lets you build interactive UIs with C# instead of JavaScript. A component is a .razor file that combines markup, Razor syntax and a @code block, and can be nested like HTML tags. It re-renders when its state changes.

HTML
@* Counter.razor (read-only: needs the Razor compiler and a Blazor project) *@
@page "/counter"

<h1>Counter</h1>
<p>Current count: @count</p>
<button class="btn" @onclick="Increment">Click me</button>

<GreetingBadge Name="Ada" />          @* using another component *@

@code {
    private int count;

    private void Increment() => count++;
}

Where the component runs is the render mode:

  • Static server rendering: the server renders HTML and sends it, like Razor Pages. No live connection. Fast and SEO-friendly.
  • Interactive Server: the component runs on the server; UI events travel over a SignalR connection (a WebSocket) and the server sends small DOM updates back. Instant startup, full .NET access, but every user holds a server connection and latency matters.
  • Interactive WebAssembly: the .NET runtime and your component code are downloaded to the browser and run there. Works offline and offloads the server, but has a larger first download.
  • Interactive Auto: starts as Interactive Server, then switches to WebAssembly once the download finishes.

A "Blazor Web App" (the default template since .NET 8) mixes these per page or per component. Choose Blazor when you want rich interactivity and want to share C# code (validation models, DTOs) between client and server; avoid it for content-heavy public sites where plain server-rendered HTML does the job, and for teams already productive with a mature JavaScript framework.

How to choose

  1. Only JSON for a mobile or JavaScript front end? Minimal APIs, or controllers for a big team.
  2. A mostly server-rendered site with forms and pages? Razor Pages (or MVC if you prefer controllers).
  3. A rich app with live updates and state? Blazor, or an API plus a JavaScript framework.
  4. Not sure? Start with Razor Pages for the site and minimal APIs for the endpoints; both can live in one project, and you can add Blazor components to a page later.

Whatever you pick, the cross-cutting parts are the same: pipeline order, authentication, validation, configuration and logging. Learning those once pays off in every model.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Razor, what does @Model.Name do when Name contains <script>?

    Razor expressions are HTML-encoded by default. Only Html.Raw or IHtmlContent values are written as markup.
  2. 2. What is the main purpose of the post-redirect-get pattern?

    After a successful POST the server redirects to a GET page. Refreshing then repeats the harmless GET instead of resubmitting the form.
  3. 3. What does [ApiController] add to a controller?

    [ApiController] enables API conventions, including automatic ModelState validation that returns a problem details response before the action executes.
  4. 4. Which Razor-based model organizes code by page, with an @page directive and a PageModel class?

    Razor Pages pairs each page template with a PageModel that has OnGet/OnPost handlers; the URL follows the file path.
  5. 5. Why should form actions bind to a dedicated input class instead of a database entity?

    Binding to an entity lets an attacker supply extra fields such as IsAdmin. A purpose-built input class lists exactly what a form may change.

Summary

  • ASP.NET Core offers minimal APIs, MVC, Razor Pages and Blazor on one shared foundation; pick by UI style and team preference, and mix them freely.
  • MVC separates controllers (decide), models (data) and views (HTML); actions return IActionResult, routing maps URLs by convention or attributes.
  • Razor syntax mixes HTML and C# with @; expressions are HTML-encoded by default, Html.Raw is the escape hatch to use sparingly.
  • Handle forms with model binding, ModelState and post-redirect-get; bind to input classes, and protect forms with antiforgery tokens.
  • [ApiController] gives controllers automatic validation and API conventions; Razor Pages organizes code by page; Blazor builds interactive components in C# with several render modes.

Next: SignalR, WebSockets and gRPC