Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 52 ยท MVC, Controllers and Razor

Blazor Overview

Understand Blazor components, the four render modes (static SSR, Interactive Server, WebAssembly, Auto), forms and streaming rendering, and when to choose Blazor.

Razor templates produce HTML on the server and then forget about it. If the page must react to a click, you write JavaScript. Blazor takes a different road: you build the user interface out of components written in C# and Razor syntax, and you handle events with C# methods instead of JavaScript. Blazor is part of ASP.NET Core, so a Blazor app is still an ASP.NET Core app with a pipeline, dependency injection and configuration.

What confuses newcomers is not the component model but the question where does my component run? Since .NET 8 a single Blazor app can render some components as plain HTML, others live on the server over a persistent connection, and others inside the browser through WebAssembly. Those choices are called render modes, and picking the right one is the main design decision in Blazor. This lesson explains the component model, the four modes, forms and streaming rendering.

Blazor components are .razor files that need the Razor compiler and a full project, which the single-file live runner does not have. So the real Blazor code below is read-only. The runnable examples are plain C# stand-ins that demonstrate the ideas (re-rendering, diffing, streaming, form validation), and each one says what part is real. For a language-side introduction, see Blazor in depth in the C# tutorial.

A component is a class with markup

A component is a .razor file. The markup sits on top, and a @code block holds state and methods. This one is a counter:

RAZOR
@page "/counter"

<h1>Counter</h1>
<p role="status">Clicked @count times</p>

<button class="btn" @onclick="Increment">Click me</button>

@code {
    private int count;

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

The compiler turns that file into a C# class that inherits from ComponentBase. @page "/counter" makes it routable, @onclick="Increment" wires a DOM event to a method, and when the handler finishes Blazor re-renders the component. Components can take parameters from their parent, accept child markup, bind two ways, and nest:

RAZOR
<ProductCard Product="item" OnAdded="HandleAdded">
    <em>Limited edition</em>
</ProductCard>

<input @bind="searchText" @bind:event="oninput" />

@code {
    [Parameter] public Product Product { get; set; } = default!;
    [Parameter] public EventCallback<Product> OnAdded { get; set; }
    [Parameter] public RenderFragment? ChildContent { get; set; }
}

Components have a lifecycle: OnInitialized(Async) runs once, OnParametersSet(Async) runs when parameters change, and OnAfterRender(Async) runs after the output reaches the browser, which is the right place for JavaScript interop. A component asks for a re-render by calling StateHasChanged(), and event handlers do that implicitly.

How re-rendering works

Blazor does not rebuild the whole page. A component produces a render tree, a lightweight description of the elements it wants. After each render, Blazor compares the new tree with the previous one and applies only the differences to the real DOM. The stand-in below has the same shape: a component exposes its current output as keyed nodes, a host re-renders after an event, and a diff finds what changed.

C# State, events and re-rendering

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 first render sends everything, later renders send only the status node, and the title is never resent. Real Blazor tracks element and attribute-level changes in a binary render batch, but the idea (re-run the component, diff, patch) is the same. Two practical consequences: keep render methods fast and free of side effects, and use @key on list items so Blazor can match old and new elements correctly.

The four render modes

Here is the part that is new since .NET 8. A component is rendered in one of these modes:

flowchart TD
    Q["Does the component need<br/>to react to the user?"] -->|"no"| S["Static SSR<br/>HTML only, no connection"]
    Q -->|"yes"| W["Where should the code run?"]
    W -->|"on the server"| IS["Interactive Server<br/>SignalR circuit"]
    W -->|"in the browser"| IW["Interactive WebAssembly<br/>.NET runtime in the page"]
    W -->|"both, server first"| IA["Interactive Auto<br/>Server now, WebAssembly later"]

Static SSR is the default; interactivity is something you opt into per component or per page.

  • Static server-side rendering (static SSR) is the default. The server renders HTML and sends it, and nothing stays connected. Pages are fast, SEO-friendly and cheap, and forms work through ordinary HTTP posts. There are no @onclick handlers, because there is nothing alive on the other side.
  • Interactive Server keeps a circuit open over SignalR (WebSocket). Click events travel to the server, your C# runs there, and UI diffs travel back. The first load is small and code never leaves your server, but each user holds server memory and every interaction pays network latency.
  • Interactive WebAssembly downloads the .NET runtime and your assemblies to the browser, where components run locally. Interactions are instant and the app can work offline, but the first load is heavier and any data access must go through an API, because the code is now running on the user's machine.
  • Interactive Auto starts with Interactive Server so the page is usable at once, downloads the WebAssembly bundle in the background, and uses it on later visits.

You turn on interactivity in Program.cs and choose modes with the @rendermode directive:

C#
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode();
RAZOR
@page "/chart"
@rendermode InteractiveServer

<ChartView Data="data" />

A mode set on a parent flows to its children, and you can also set it for the whole app on the Routes component. Most real apps leave the shell static and make only the interactive islands (a search box, a chart, a cart) interactive.

Interactive components are prerendered by default: the server first renders their HTML so the page appears immediately, then the component starts again in its interactive mode. That means OnInitializedAsync can run twice, and code that loads data or talks to the user's browser needs care. In .NET 10 the [PersistentState] attribute can carry state computed during prerendering across to the interactive run so you do not load it twice.

Streaming rendering

Static SSR has a clever trick for slow data. Normally the server waits for OnInitializedAsync to finish before sending anything. With streaming rendering (@attribute [StreamRendering]), the server sends the page right away with whatever it has, such as a "Loading..." message, keeps the response open, and when the slow work finishes it streams the update, which a tiny script swaps into place. The browser shows content sooner without any WebSocket or WebAssembly.

The stand-in below does the same thing with a plain Kestrel endpoint. The shell is flushed first, the slow part arrives later, and the client proves the first line was readable before the server had produced the second.

C# Sending the shell first, the data later

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 first two lines are read while slowPartSent is still False; only the third line arrives after the delay. That is the user-visible benefit: the page frame appears in milliseconds and the slow data fills in afterwards.

Forms and validation

Blazor forms use EditForm with a model and DataAnnotationsValidator. In static SSR the form posts to the server like a normal HTML form, so the model comes from the request with [SupplyParameterFromForm]; in interactive modes the same markup validates as the user types.

RAZOR
<EditForm Model="Model" OnValidSubmit="Save" FormName="signup" Enhance>
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="Model.Email" />
    <ValidationMessage For="() => Model.Email" />

    <InputNumber @bind-Value="Model.Age" />
    <button type="submit">Join</button>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private SignupModel Model { get; set; } = new();

    private void Save() { /* the model is valid here */ }
}

The validation itself is the same System.ComponentModel.DataAnnotations machinery you may already use in APIs (see Model Validation). The component's DataAnnotationsValidator simply runs it against the edited model and shows messages. This part can run for real:

C# The validation behind EditForm

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.

When to choose Blazor

Blazor shines when your team already writes C#, when you want one language and one set of models across server and UI, when the app is an interactive line-of-business tool (dashboards, admin panels, internal apps), or when you want to share validation and DTO code with the client. Think twice when:

  • the site is mostly content that must load instantly everywhere and rank in search, where static SSR or plain Razor Pages is lighter;
  • you need a huge ecosystem of ready-made front-end widgets, where the JavaScript world still has more choice (Blazor can call JavaScript through interop, but it is an extra bridge);
  • you cannot afford a persistent connection per user (Interactive Server) or a multi-megabyte first download (WebAssembly).

A sensible default today is a Blazor Web App with static SSR pages and a few interactive islands, adding render modes only where users need them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default render mode of a component in a Blazor Web App?

    Components are rendered as static HTML unless you opt into an interactive mode with @rendermode. Static components have no live connection, so they cannot respond to @onclick.
  2. 2. In Interactive Server mode, where does the C# code for a button click run?

    The click event travels to the server over the circuit, the handler runs there, and Blazor sends the resulting UI differences back to the browser.
  3. 3. What does Interactive Auto do?

    Auto gives a fast first interaction through the server circuit while the WebAssembly bundle downloads in the background, and uses WebAssembly on later visits.
  4. 4. Why can OnInitializedAsync run twice for an interactive component?

    Prerendering produces HTML on the server first, then the interactive runtime creates the component again. Persisting state from prerendering avoids loading the data twice.

Summary

  • Blazor builds UI from C# components (.razor files) that handle events with C# methods and re-render when state changes.
  • After each render Blazor diffs the render tree and patches only what changed; use @key on lists.
  • Render modes: static SSR (default, HTML only), Interactive Server (SignalR circuit), Interactive WebAssembly (runs in the browser) and Interactive Auto (server first, then WebAssembly).
  • Interactive components are prerendered, so initialization can run twice; persist state to avoid duplicate work.
  • Streaming rendering sends the page shell at once and streams slow data in later, with no extra connection.
  • EditForm plus DataAnnotationsValidator reuses the standard data-annotations validation.
  • Choose Blazor for C# teams and interactive apps; prefer static SSR or Razor Pages for content-heavy pages.

Next: Data Access without an ORM