In the lesson «ASP.NET Core MVC: controllers, views and models» every click brought a new page from the server. But if we want a counter to grow the moment a button is pressed, or a button to become active while we type, we usually need JavaScript. Blazor lets you build such interactive UI in C#, out of components — and the same component can run on the server or inside the browser with WebAssembly. In this lesson you will build a “Study planner” app, start it on a local port, look at the HTML the server sends with curl, and check the interactivity by pressing buttons in a browser.
The Blazor Web App and render modes
dotnet new blazor -o Planner --interactivity Server --empty creates an empty Blazor Web App. The --interactivity option can be None, Server, WebAssembly or Auto, and --all-interactive makes every page interactive. Every component works in a render mode, which decides where it runs and whether it is interactive:
| Mode | Where the code runs | Characteristics |
|---|---|---|
| Static SSR (the default) | on the server, once | finished HTML; button events do not work, forms use an ordinary POST |
InteractiveServer | on the server; events arrive over a SignalR connection (a circuit) | starts fast and the code never reaches the browser; needs a constant connection and server memory for every user |
InteractiveWebAssembly | in the browser — .NET is downloaded as WebAssembly | after loading, the UI works without a constant server connection; the first download is big and the code is visible to the user |
InteractiveAuto | first on the server, later in the browser | Server mode until the WebAssembly files are downloaded, WebAssembly on later visits |
You give a page its mode with the directive @rendermode InteractiveServer. On the server this needs two lines: AddRazorComponents().AddInteractiveServerComponents() registers the services, and MapRazorComponents<App>().AddInteractiveServerRenderMode() maps the components to addresses. Our Program.cs has two more things — a service and a small API; we will come back to them at the end of the lesson.
using Planner.Components;
using Planner.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddSingleton<InMemoryTaskService>();
builder.Services.AddHttpClient<ITaskService, ApiTaskService>(client =>
client.BaseAddress = new Uri(builder.Configuration["ApiBaseUrl"] ?? "http://localhost:5091/"));
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.UseAntiforgery();
app.MapStaticAssets();
app.MapGet("/api/tasks", (InMemoryTaskService store) => store.GetAllAsync());
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();Program.cs: Razor components, the interactive Server mode, a service and the /api/tasks endpointComponents and parameters
ComponentDefinition
A .razor file made of markup and an @code block. The compiler turns it into a C# class derived from ComponentBase. A component's name starts with a capital letter, and it is used like an HTML tag: <Greeting Name="Aysel" />.
<section class="greeting">
<h2>Hello, @Name!</h2>
@ChildContent
</section>
@code {
[Parameter, EditorRequired]
public string Name { get; set; } = "";
[Parameter]
public RenderFragment? ChildContent { get; set; }
}Components/Greeting.razor: a component with two parametersA public property marked [Parameter] is a component parameter — the caller passes it as an attribute. [EditorRequired] makes the parameter mandatory: if you write <Greeting />, the build shows the warning RZ2012: Component 'Greeting' expects a value for the parameter 'Name', but a value may not have been provided. ChildContent of type RenderFragment is a special parameter: everything between the opening and closing tag goes into it. The @page "/" directive turns a component into a page with an address:
@page "/"
<PageTitle>Planner</PageTitle>
<h1>Study planner</h1>
<Greeting Name="Aysel">
<p>You have @lessons lessons today.</p>
</Greeting>
<Greeting Name="Murad" />
@code {
private int lessons = 3;
}Components/Pages/Home.razor: there is no @rendermode, so the page is static SSRStart the app with dotnet run --urls http://localhost:5091 and look at the server's answer (we cut away the template's service parts with grep):
curl -s localhost:5091/ | grep -A5 '<h1>'Expected output
<h1>Study planner</h1>
<section class="greeting"><h2>Hello, Aysel!</h2>
<p>You have 3 lessons today.</p></section>
<section class="greeting"><h2>Hello, Murad!</h2>
</section>Greeting has no ChildContentEvents and data binding
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @count</p>
<button @onclick="Increment">Add @step</button>
<button @onclick="() => count = 0">Reset</button>
<label>Step: <input type="number" @bind="step" /></label>
@code {
private int count;
private int step = 1;
private void Increment() => count += step;
}Components/Pages/Counter.razor: an interactive counter@onclick="Increment" attaches a method to the button, and @onclick="() => count = 0" a lambda — just like in the lesson «Delegates, lambdas and events». @bind="step" is two-way binding: the field shows the value of step, and when the user changes it and leaves the field (onchange), the new value is written to step. After every event handler Blazor re-renders the component by itself and sends only the changed parts to the browser. The server first delivers the page through prerendering, as plain HTML:
curl -s localhost:5091/counter | grep -E '<h1>|<p role|<button>|<label>' | sed 's/<!--.*-->//'Expected output
<h1>Counter</h1> <p role="status">Current count: 0</p> <button>Add 1</button> <button>Reset</button> <label>Step: <input type="number" value="1" /></label>
After opening /counter in a browser, we tested the page as a user would. The results:
| Action | The page shows |
|---|---|
Press Add 1 three times | Current count: 3 |
Type 5 into Step and leave the field | the button becomes Add 5 |
Press Add 5 | Current count: 8 |
Child components, EventCallback and the lifecycle
The to-do list is made of two components: the Todo page keeps the list, and TodoItem shows one row. A child component should not change its parent's data on its own but tell the parent about it — that is what EventCallback is for.
<li>
<input type="checkbox" @bind="Item.Done" @bind:after="() => OnChanged.InvokeAsync()" />
<span class="@(Item.Done ? "done" : "")">@Item.Title</span>
<button @onclick="() => OnRemove.InvokeAsync(Item)">Remove</button>
</li>
@code {
[Parameter, EditorRequired]
public TodoTask Item { get; set; } = default!;
[Parameter]
public EventCallback OnChanged { get; set; }
[Parameter]
public EventCallback<TodoTask> OnRemove { get; set; }
}Components/TodoItem.razor: two EventCallback parameters@page "/todo"
@rendermode InteractiveServer
@inject ITaskService TaskService
<h1>To-do (@Tasks?.Count(t => !t.Done) left)</h1>
@if (Tasks is null)
{
<p>Loading...</p>
}
else
{
<ul>
@foreach (TodoTask task in Tasks)
{
<TodoItem Item="task" OnChanged="StateHasChanged" OnRemove="Remove" />
}
</ul>
<input @bind="newTitle" @bind:event="oninput" placeholder="New task" />
<button @onclick="Add" disabled="@string.IsNullOrWhiteSpace(newTitle)">Add</button>
}Components/Pages/Todo.razor, the markup part@code {
[PersistentState]
public List<TodoTask>? Tasks { get; set; }
private string newTitle = "";
protected override async Task OnInitializedAsync()
{
Console.WriteLine($"OnInitializedAsync, interactive: {RendererInfo.IsInteractive}, restored: {Tasks is not null}");
Tasks ??= await TaskService.GetAllAsync();
}
private void Add()
{
Tasks!.Add(new TodoTask { Title = newTitle.Trim() });
newTitle = "";
}
private void Remove(TodoTask task) => Tasks!.Remove(task);
}Components/Pages/Todo.razor, the @code partEventCallback is a reference to a method of the parent; when the child calls it with InvokeAsync, Blazor runs the method and re-renders the parent. This helped us find a real bug in our project. At first TodoItem had only @bind="Item.Done": ticking the box marked the task as done, but the heading stayed at To-do (2 left). The reason: the child handles the event and re-renders only itself. The fix was @bind:after="() => OnChanged.InvokeAsync()": the parent receives the news through OnChanged="StateHasChanged", and the heading updates at once.
| Method | When it is called |
|---|---|
OnInitialized / OnInitializedAsync | once when the component instance is created — the place to load data |
OnParametersSet / OnParametersSetAsync | the first time and every time the parent changes the parameters |
OnAfterRender(bool firstRender) | after the DOM is updated; firstRender is true the first time — for JavaScript calls |
StateHasChanged() | tells the component to re-render (for example after a timer) |
Dispose | when the component leaves the page, if it has @implements IDisposable |
The line we wrote in OnInitializedAsync appeared like this in the server console when /todo was opened in a browser:
OnInitializedAsync, interactive: False, restored: False
OnInitializedAsync, interactive: True, restored: TrueDuring prerendering the component is created once and the HTML is sent; then, when the SignalR connection is set up, a new instance is created and OnInitializedAsync runs a second time. So that the data is not loaded twice, we used the .NET 10 attribute [PersistentState]: Tasks loaded during the prerender is written into the page and restored in the interactive instance (restored: True), so Tasks ??= ... skips the second load. RendererInfo.IsInteractive tells whether the component is interactive at the moment.
DI in components and calling an API
The directive @inject ITaskService TaskService takes the service from the DI container and stores it in a property — the component version of the constructor injection from the lesson «Dependency injection in .NET». In Server mode a component may call services directly. In WebAssembly the code runs in the browser: it has no way to the database, so the data comes through an HTTP API. We set it up that way from the start: the component knows only the interface, and Program.cs gives it an implementation that uses HttpClient.
namespace Planner.Services;
public class TodoTask
{
public string Title { get; set; } = "";
public bool Done { get; set; }
}
public interface ITaskService
{
Task<List<TodoTask>> GetAllAsync();
}Services/TaskService.cs: the model and the contract; InMemoryTaskService waits 300 ms and returns three taskspublic class ApiTaskService(HttpClient http) : ITaskService
{
public async Task<List<TodoTask>> GetAllAsync() =>
await http.GetFromJsonAsync<List<TodoTask>>("api/tasks") ?? [];
}AddHttpClient<ITaskService, ApiTaskService> gives it an HttpClient with a base addresscurl -s -w '\n' localhost:5091/api/tasks
curl -s localhost:5091/todo | grep -o '<h1>[^<]*</h1>'Expected output
[{"title":"Read the Blazor lesson","done":false},{"title":"Solve 5 C# tasks","done":true},{"title":"Revise LINQ","done":false}]
<h1>To-do (2 left)</h1>/todo page is prerendered already with the data from the APIChecking in the browser: ticking “Revise LINQ” changed the heading to To-do (1 left), and after “Read the Blazor lesson” it became To-do (0 left). While typing Build a Blazor page into the field, the Add button became active (@bind:event="oninput" and disabled); after pressing it the list had four tasks, the heading went back to To-do (1 left) and the field was cleared. To replace the fake store with a real API, we did not touch a single letter of the component.
Summary and practice
- The render mode chooses where a component runs: static SSR, Server (SignalR), WebAssembly (the browser) or Auto.
- A component is markup +
@code;[Parameter]passes data from parent to child, andEventCallbackpasses events from child to parent. @onclickconnects an event to a method and@bindcreates two-way binding; after an event the component re-renders by itself.OnInitializedAsyncloads data; with prerendering it runs twice, and[PersistentState]removes the repetition.
Task 1: predict the counter
Problem
On a freshly opened /counter page, these actions are done: Add 1 twice; type 5 into Step and leave the field; Add 5 once; Reset; Add 5 again. What does the page show after each step?
Show solutionHide solution
Solution
Add 1 twice: count goes 0 → 1 → 2.2)
@bind sets step to 5 on onchange; the button becomes Add 5 (the counter stays at 2).3)
Add 5: 2 + 5 = 7.4) The
Reset lambda sets count = 0: 0. step does not change and stays 5.5)
Add 5: 0 + 5 = 5.Checked in a browser:
Current count: 2, 7, 0, 5.Task 2: a rating component that supports `@bind-Value`
Problem
Write a five-star Rating component: the Value parameter is the number of selected stars, and clicking a star sends the new value to the parent. The parent must be able to use it as <Rating @bind-Value="score" />. Why does the loop need the line int star = i;?
Show solutionHide solution
Solution
[Parameter] public int Value { get; set; } and [Parameter] public EventCallback<int> ValueChanged { get; set; } — the Value + ValueChanged pair is what makes @bind-Value possible.2) The markup:
@for (int i = 1; i <= 5; i++) { int star = i; <button @onclick="() => ValueChanged.InvokeAsync(star)">@(star <= Value ? "★" : "☆")</button> }3) The parent:
<Rating @bind-Value="score" /> and <p>Your score: @score</p>, with score = 3.4) In the browser: first
★★★☆☆ and Your score: 3, after the fifth star ★★★★★ and Your score: 5.5) Without
int star = i;, all the lambdas capture the same for variable i, which is already 6 at click time: in our check, pressing any button gave Your score: 6. This is the closure trap from the lesson «Delegates, lambdas and events».Remember
- In a Blazor Web App pages are static SSR by default; interactivity comes from
@rendermode:InteractiveServer,InteractiveWebAssembly,InteractiveAuto. - Server mode sends events to the server over a SignalR connection; WebAssembly runs the code in the browser, so no secrets belong there.
[Parameter],[EditorRequired]andChildContentpass data into a component;@pagemakes it a page.@onclick,@bind,@bind:event="oninput"and@bind:afterconnect the UI with C# code.EventCallbackcalls the parent and re-renders it; aValue+ValueChangedpair gives@bind-Value.@injecttakes a service from DI;OnInitializedAsyncruns twice with prerendering —[PersistentState](.NET 10) fixes that.