Skip to content
Tutorials Center
My learning

Topics

Lesson 145 of 182 ยท ASP.NET Core

Blazor Components

Learn Blazor components in depth - parameters, child content, lifecycle, EventCallback, cascading values, state containers and EditForm validation - with real Blazor components rendered by runnable C# code.

Blazor is the part of ASP.NET Core for building interactive web UI in C# instead of JavaScript. You write components: reusable pieces of UI that combine markup with C# logic. A page is a component, a button with a counter is a component, a table row is a component, and components nest inside each other like HTML elements. State changes in C# make the framework re-render the affected components and update the browser's DOM for you.

The MVC, Razor Pages and Blazor lesson introduced Blazor next to the other UI models. This lesson goes deep on the component model itself: parameters, child content, the lifecycle, passing events up, sharing state, and forms with validation. Our in-browser runner has no Razor compiler, which normally turns .razor files into C# classes during the build. But the Blazor runtime (ComponentBase, RenderTreeBuilder, EditContext, HtmlRenderer) is part of the ASP.NET Core shared framework, so we can write components in plain C#, the code the Razor compiler would have generated, and run them for real. You will see actual Blazor behavior: re-renders, lifecycle calls, validation. The matching .razor source is shown read-only next to each idea so you can recognize it in a real project.

Hosting models in one table

The component code is the same everywhere; what differs is where it runs:

Mode Where components run Interactivity Trade-off
Static server rendering On the server, once per request None; links and forms are normal HTTP Fastest first paint, no live connection
Interactive Server On the server; UI events and DOM updates travel over a SignalR connection Full Tiny download, but latency matters and each user holds server memory
Interactive WebAssembly In the browser, in .NET compiled to WebAssembly Full Works offline and costs no server per user, but a larger first download
Interactive Auto Server first, then WebAssembly once it has downloaded Full Best start-up and best long-term behavior, most moving parts

You choose per component or per page with render-mode attributes. The examples below use the same engine as static server rendering (HtmlRenderer): it renders a component to HTML, which lets us watch the real component model without a browser.

The render cycle

Blazor components do not edit the DOM. They describe what the UI should look like right now, and the framework works out the difference from last time.

flowchart LR
    E["Event<br/>(click, input)"] --> H["Your C# handler<br/>changes fields"]
    H --> S["StateHasChanged<br/>(automatic after events)"]
    S --> B["BuildRenderTree<br/>produces a render tree"]
    B --> D["Diff against<br/>the previous tree"]
    D --> P["Apply only the<br/>changes to the DOM"]

A component's markup is a function of its state; the framework diffs the new render tree against the old one and patches only what changed.

This is why a component's markup is just a method. BuildRenderTree(RenderTreeBuilder builder) appends elements, attributes, text and child components to a flat list. The numbers you will see in generated code (OpenElement(0, "div")) are sequence numbers: stable ids of each place in the source code, which let the diff algorithm match old and new frames quickly. In .razor files you never write any of this.

Anatomy of a component

Here is a small component in a .razor file (read-only; you cannot compile this in our runner):

RAZOR
@* Badge.razor *@
<span class="badge @Kind">
    @Text
    @ChildContent
</span>

@code {
    [Parameter] public string Text { get; set; } = "";
    [Parameter] public string Kind { get; set; } = "info";
    [Parameter] public RenderFragment? ChildContent { get; set; }
}

And this is the class it compiles to, which is runnable. A parameter is a public property marked [Parameter]; the parent sets it like an HTML attribute (<Badge Text="New" Kind="success" />). RenderFragment is a delegate that renders markup, which is how a parent passes child content into a component (like the content between tags in HTML). Blazor HTML-encodes text for you, so the <script> text below is safe:

C# Components, parameters and child content

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.

Each Badge got its own parameters from the list. The attribute value is built by a plain C# expression ("badge " + Kind), the loop is a plain foreach, and the malicious product name came out as &lt;script&gt;.... Blazor only emits raw HTML if you explicitly use MarkupString, which you should do only for content you fully trust (never for user input).

When a parameter is only ever set by the parent, give it a default value and treat it as input: do not write to it from inside the component and expect the parent to see the change. For two-way flow, expose a value plus an EventCallback (next sections) or use @bind-Value on the parent's side, which is shorthand for exactly that pair.

The component lifecycle

Components go through a fixed sequence of methods you can override. Doing the right work in the right method is the biggest difference between a component that behaves and one that flickers or loops.

stateDiagram-v2
    [*] --> SetParameters: created, parameters assigned
    SetParameters --> OnInitialized: first time only
    OnInitialized --> OnParametersSet
    SetParameters --> OnParametersSet: later parameter changes
    OnParametersSet --> ShouldRender: not the first render
    OnParametersSet --> Render: first render
    ShouldRender --> Render: returns true
    ShouldRender --> Idle: returns false
    Render --> OnAfterRender
    OnAfterRender --> Idle
    Idle --> SetParameters: parent re-renders with new values
    Idle --> Render: StateHasChanged or event
    Idle --> [*]: parent removes the component (Dispose)

Initialization runs once; parameter handling and rendering repeat for the life of the component; Dispose runs when the parent removes it.

Method Runs Use it for
OnInitialized / OnInitializedAsync once, before the first render loading data the component needs
OnParametersSet / OnParametersSetAsync after the first init and every time the parent supplies parameters reacting to a changed parameter (reload when Id changes)
ShouldRender before each re-render (not the first) skipping renders when nothing visible changed
OnAfterRender / OnAfterRenderAsync(bool firstRender) after the DOM was updated, only in interactive modes JavaScript interop, focusing an element
Dispose / DisposeAsync when the component is removed unsubscribing from events, cancelling work

The next program logs every call while a parent re-renders. Pay attention to two things: a child whose parameters did not change is not even asked to re-render, and OnAfterRender never fires in this static render because no DOM exists to update:

C# Watching the lifecycle

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.

Changing the title re-rendered Dashboard, but TotalCard received the same int, so Blazor skipped it completely. This parameter change detection is automatic for simple types (numbers, strings, enums, DateTime, and so on). For complex types (your own classes, collections) Blazor cannot tell whether they changed internally, so it assumes they did and re-renders the child every time. The same applies to a RenderFragment parameter. That matters for performance with big trees; use ShouldRender, @key and smaller components to control it. The log shows it twice: after the title change, and after the second ChangeTotal(42), the parent re-rendered but the child's parameters were identical, so nothing ran in the child.

Two traps from the lifecycle:

  • Do not load data in OnAfterRender for the first display. It runs after the first paint, so the user sees an empty screen, and any state change there causes another render. Load in OnInitializedAsync, and use OnAfterRenderAsync(firstRender) only for JavaScript interop.
  • Async methods render twice. With OnInitializedAsync, Blazor renders once when the first await yields (showing a "loading" state) and again when the task completes. Write markup that handles null data. (In static server rendering the framework waits for the data before sending HTML unless you enable streaming rendering.)

Passing events up: EventCallback

Data flows down through parameters. Events flow up through EventCallbacks: delegate-like parameters the parent fills in with a handler. Use EventCallback or EventCallback<T> rather than a plain Action or Func: when invoked, it automatically calls StateHasChanged on the component that owns the handler, so the parent re-renders without you remembering to. A CascadingValue goes the other way down the tree: it provides a value to every descendant, so deep components can read a theme or the current user without passing the parameter through each level.

RAZOR
@* Parent.razor (read-only) *@
<CascadingValue Value="@theme">
    <ColorPicker OnPicked="HandlePicked" />
</CascadingValue>
<p>Picked: @picked (theme: @theme)</p>

@code {
    private string theme = "dark";
    private string picked = "none";
    private void HandlePicked(string color) => picked = color;   // no StateHasChanged needed
}
C# EventCallback and CascadingValue

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 picker never mentioned the parent and never received the theme through a [Parameter]: it asked for a [CascadingParameter] and the nearest matching CascadingValue supplied it. The parent's handler only assigned a field, yet the page's HTML changed: EventCallback.InvokeAsync re-rendered the component that owns the handler. If you used a Func<string, Task> instead, you would have to call StateHasChanged() yourself.

Sharing state between components

Parameters and cascading values handle parent-to-child flow. For state that unrelated components need (a shopping cart count in the header and a cart list on the page), use a state container: an ordinary service registered with dependency injection that holds the data and raises an event when it changes. Components @inject it, subscribe in OnInitialized, and call InvokeAsync(StateHasChanged) in the handler (InvokeAsync marshals onto the renderer's thread). They must unsubscribe in Dispose, or the long-lived service keeps removed components alive: the same leak as in INotifyPropertyChanged and MVVM.

The lifetime you register decides who shares the state: in Interactive Server mode a scoped service lives as long as the user's circuit (one per browser tab); a singleton is shared by all users, which is almost never what you want for user data. In WebAssembly, scoped and singleton behave the same, because there is only one user.

C# A state container shared by two components

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.

Adding to the cart updated both components even though neither knows the other exists. The final line shows both components still subscribed, because the renderer (and so the components) is still alive; in a real app, navigating away removes the components and calls their Dispose, which removes the handlers. For larger apps, people also use libraries such as Fluxor or hand-written services with IObservable, but the idea stays the same: one source of truth, a change event, and components that re-render in response.

Forms and validation

Forms in Blazor are built on three pieces from Microsoft.AspNetCore.Components.Forms:

  • an EditContext, which tracks one model object: which fields were edited, and which validation messages exist;
  • EditForm, a component that creates (or receives) an EditContext, renders the <form>, and runs your OnValidSubmit / OnInvalidSubmit callbacks;
  • input components (InputText, InputNumber, InputDate, InputSelect, InputCheckbox) and ValidationMessage, which bind to model properties through @bind-Value and add CSS classes (modified, valid, invalid) to the HTML element.

Validation usually comes from the same DataAnnotations attributes ([Required], [Range], [StringLength], [EmailAddress]) used by validation and problem details, activated by putting <DataAnnotationsValidator /> inside the form. In a .razor file:

RAZOR
@* SignUpForm.razor (read-only) *@
<EditForm Model="model" OnValidSubmit="Save" OnInvalidSubmit="ShowErrors" FormName="signup">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label>Name <InputText @bind-Value="model.Name" /></label>
    <ValidationMessage For="() => model.Name" />

    <label>Age <InputNumber @bind-Value="model.Age" /></label>
    <ValidationMessage For="() => model.Age" />

    <button type="submit">Create account</button>
</EditForm>

@code {
    [SupplyParameterFromForm] private SignUp model { get; set; } = new();
    private Task Save() { /* store the account */ return Task.CompletedTask; }
    private void ShowErrors() { }
}

All the logic lives in the EditContext, so we can drive it directly. The program below validates a model, shows how the CSS classes change when a field is edited, and adds a server-side error (a duplicate e-mail found only after calling the database) through a ValidationMessageStore, which shows up next to the field exactly like an annotation error would.

C# EditContext, DataAnnotations and server errors

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.

Read the states in order. On load nothing is marked invalid, because users should not be scolded before they type. The first submit validates the whole model and all three errors appear. Editing a field marks it modified and revalidates that field, flipping invalid to valid live, which is how the red borders turn green as users fix input. The server-side error went through the store, was cleared on the next validation round, and the form finally succeeded. The CSS class strings are exactly what the input components put on the HTML element, so you style .invalid and .valid.modified in your stylesheet.

Client-side validation is for convenience, never for security. In Interactive WebAssembly the model runs in the user's browser, and any HTTP endpoint you call from it can be called by anyone with curl. Validate again on the server, using the same attributes or problem details, and enforce authorization on the server (see authentication and authorization).

Performance and good habits

  • Use @key on items in a loop whose order or content changes, so the diff moves existing elements instead of rebuilding them (we used SetKey in the first example).
  • Keep components small. Splitting a big component lets Blazor skip the parts whose parameters did not change.
  • Avoid doing work inside BuildRenderTree. It runs on every render. Compute values in lifecycle methods or cache them in fields.
  • Virtualize long lists with the Virtualize component, which renders only the visible rows.
  • Dispose what you subscribe to. Events, timers, CancellationTokenSources and JavaScript interop references all need cleanup in Dispose.
  • Handle exceptions at the boundary. Wrap risky areas in ErrorBoundary, so one failing widget does not take the page down.
  • Prefer static server rendering for content pages and add interactivity only where it earns its keep. It is the fastest start and simplest to cache.
  • Remember the threading rule. A component runs on its renderer's synchronization context; code arriving from elsewhere (timers, other threads, service events) must use InvokeAsync(...) before touching state or calling StateHasChanged.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A parent re-renders and passes the same int value to a child component. What does Blazor do for the child?

    For simple immutable types Blazor compares the old and new parameter values and skips the child when nothing changed. Complex types and RenderFragments are assumed to have changed.
  2. 2. Where should you load the data a component needs for its first display?

    OnInitializedAsync runs once before the first render. OnAfterRender runs after the first paint and is meant for work that needs the rendered DOM, such as JavaScript interop.
  3. 3. Why prefer EventCallback over Action for a component's event parameter?

    EventCallback.InvokeAsync calls StateHasChanged on the receiver for you, and it handles both sync and async handlers.
  4. 4. A state-container service raises Changed, and components subscribed in OnInitialized. What must they also do?

    A long-lived service holds references to subscribers, so an unremoved handler leaks the component. The handler may run on another thread, so it marshals through InvokeAsync.
  5. 5. Which statement about form validation in Blazor is correct?

    EditContext can be driven directly, validators and custom stores add messages to it, and anything coming from a browser must be validated again on the server.

Summary

  • A Blazor component is a class (usually generated from a .razor file) whose BuildRenderTree describes the UI; the framework diffs render trees and patches the DOM.
  • Parameters flow down, EventCallbacks flow up, and CascadingValue provides values to all descendants.
  • Lifecycle: OnInitialized once, OnParametersSet on every parameter update, ShouldRender, render, OnAfterRender (interactive modes only), Dispose.
  • Unchanged simple parameters skip the child; complex parameters and RenderFragments do not.
  • Share state across unrelated components with a DI service that raises a change event; unsubscribe in Dispose and choose the service lifetime deliberately.
  • Forms use EditContext, input components and validators such as DataAnnotationsValidator; always validate again on the server.

Next: OpenAPI Docs and GraphQL