Blazor Learning Path
Blazor Learning Path, Part 1: The Fundamentals
October 28, 2026 · 16 min read
Blazor, C#, .NET, Razor, Interview Prep
If you're coming to Blazor from React or from server-side .NET, you want one path through it instead of a pile of tutorials written for different versions. This series is that path, in the same shape as the React one:
- The fundamentals (this post): components, binding, events, routing, the lifecycle and render modes.
- Building real features: forms and validation, dependency injection, calling APIs, state, auth, localization and JavaScript interop.
- Advanced Blazor: render modes in depth, prerendering, streaming, performance, security, error handling, testing and project structure.
- Blazor vs React: the same ideas in two stacks.
Each part teaches the current standard from Microsoft's .NET 10 docs and the Blazor Web App template. Real projects don't always look like the docs, so where a common enterprise pattern differs, there's an In the wild note explaining why teams choose it and what the trade-off is. Every code sample here compiles against .NET 10; the running example is a small book club app.
What Blazor is
Blazor lets you build web UI with C# and Razor instead of JavaScript. You write components: .razor files that mix HTML markup with C#. Blazor renders them and keeps the page in sync when their state changes.
Where that C# runs is the interesting part, and it's a choice you make per component:
- On the server, either as plain HTML (static server-side rendering) or interactively over a real-time connection.
- In the browser, on a .NET runtime compiled to WebAssembly.
Since .NET 8, one project type covers all of it: the Blazor Web App. We'll get to render modes at the end of this post; everything before that works the same wherever the component runs.
In the wild: plenty of production apps still use the older hosted Blazor WebAssembly layout: a
Clientproject, aServerproject with API controllers, and aSharedproject. It was the standard before .NET 8 and it still works. The gotcha is for newcomers: tutorials, samples and Stack Overflow answers now mix two hosting models, and advice for one (render modes,@rendermode, streaming) doesn't apply to the other. When you join a project, check which model it uses before copying anything. For new apps, start from the Blazor Web App template.
Components and parameters
A component is a .razor file. Markup at the top, C# in an @code block. The file name is the component name, and it must start with a capital letter.
@* BookCard.razor *@
<div class="book-card">
<h3>@Title</h3>
<p>by @Author</p>
@if (IsFavourite)
{
<span class="badge">Favourite</span>
}
@ChildContent
<button @onclick="() => OnFavourite.InvokeAsync(Title)">Favourite</button>
</div>
@code {
[Parameter, EditorRequired] public string Title { get; set; } = "";
[Parameter] public string Author { get; set; } = "Unknown";
[Parameter] public bool IsFavourite { get; set; }
[Parameter] public RenderFragment? ChildContent { get; set; }
[Parameter] public EventCallback<string> OnFavourite { get; set; }
}
The pieces:
[Parameter]marks a public property the parent can set, like props in React.[EditorRequired]makes the compiler warn when a parent forgets it.@switches to C#:@Titlewrites a value, and@ifand@foreachare control flow.RenderFragment ChildContentreceives whatever markup the parent puts between the tags. That's how you build wrapper components like cards and dialogs.EventCallback<T>is how a child tells its parent something happened. Data flows down through parameters; events flow up through callbacks.
Using it:
@* Shelf.razor *@
@page "/shelf"
@rendermode InteractiveAuto
<BookCard Title="Dune" Author="Frank Herbert"
IsFavourite="@(favourite == "Dune")"
OnFavourite="MarkFavourite">
<p>Book club pick for March.</p>
</BookCard>
@code {
private string? favourite;
private void MarkFavourite(string title) => favourite = title;
}
When the child invokes OnFavourite, Blazor runs MarkFavourite on the parent and re-renders the parent automatically. That's one reason to use EventCallback rather than a plain Action: it knows which component to refresh.
Two rules, the same as in any component framework: don't change your own parameters (the parent will overwrite them on its next render; copy them into a private field if you need to modify them), and keep rendering free of side effects.
Styling uses CSS isolation: put a BookCard.razor.css next to the component and its rules apply only to that component. Blazor rewrites the selectors with a unique attribute at build time.
/* BookCard.razor.css: scoped to BookCard only */
.book-card {
border: 1px solid #ddd;
border-radius: 8px;
padding: 1rem;
}
Pages vs components
Technically Blazor has only one thing: the component. A page is simply a component with an @page "/route" directive, which registers it with the router so the browser can navigate to it. Everything without @page is a reusable component that pages (or other components) place in their markup, like <BookCard> above.
Real projects keep the two apart by folder, so you can tell at a glance what's a screen and what's a building block. The .NET 8+ Blazor Web App template lays it out like this:
Components/
Pages/ routable screens, each starts with @page
Shelf.razor
BookDetails.razor
Layout/ the shell around every page
MainLayout.razor
NavMenu.razor
Shared/ your reusable components, no @page (add this folder yourself)
BookCard.razor
StarRating.razor
Older templates and many existing codebases use top-level Pages/ and Shared/ folders instead. It's the same idea with different paths.
The split that keeps an app maintainable:
- Pages own the screen. They read route parameters, load data, and decide what happens on save.
- Components take parameters and raise
EventCallbacks. They don't know which page they're on, which is exactly what makes them reusable. - Keep pages thin. When a page grows long, the extra markup is usually a component waiting to be extracted.
- A page can have more than one
@pagedirective (for example/books/{Id:int}and/books/{Id:int}/edit). Technically a component with@pagecan also be used as a child, but avoid it; it blurs the line.
Single file or code-behind
There are two ways to write the C# part of a component, and you'll meet both in real codebases.
1. Single file. Markup and an @code block in one .razor file, like BookCard above. This is what the templates and most docs use, and it's ideal for small components.
2. Code-behind. The markup stays in BookTile.razor, and the C# moves to a partial class in BookTile.razor.cs next to it. The compiler merges the two halves into one class.
@* BookTile.razor: markup only *@
<div class="book-card">
<h3>@Title</h3>
<p>by @Author</p>
<button @onclick="Favourite">Favourite</button>
</div>
// BookTile.razor.cs
using Microsoft.AspNetCore.Components;
namespace BookClub.Components.Shared; // must match the .razor file's namespace
public partial class BookTile
{
[Parameter, EditorRequired] public string Title { get; set; } = "";
[Parameter] public string Author { get; set; } = "Unknown";
[Parameter] public EventCallback<string> OnFavourite { get; set; }
[Inject] private ILogger<BookTile> Logger { get; set; } = default!; // @inject becomes [Inject]
private async Task Favourite()
{
Logger.LogInformation("Favourited {Title}", Title);
await OnFavourite.InvokeAsync(Title);
}
}
The details that trip people up:
- The class must be
partial, with the same name as the file. - The namespace must match the one Blazor generates for the
.razorfile: the project's root namespace plus the folder path (BookClub.Components.Sharedhere). If it doesn't, you get two different classes, and the markup can't see your fields and methods. @injectbecomes an[Inject]property, and anything you'd write in@code(parameters, fields, lifecycle overrides likeOnInitializedAsync) moves into the class unchanged.- Visual Studio and Rider nest
BookTile.razor.csunderBookTile.razorin the file tree, collapsed by default.
You'll also see a third, older style in codebases that predate partial-class support: a separate base class (BookTileBase : ComponentBase) and @inherits BookTileBase at the top of the .razor file. It works, but members the markup uses must be protected rather than private. New code should use the partial class.
Which to pick? Both compile to the same thing, so it's a team convention, not a technical decision. Single file keeps everything in view and suits small and medium components. Code-behind suits components with a lot of logic, and some developers simply prefer full C# tooling in a .cs file. What matters is picking one default and sticking to it.
In the wild: it's common to find codebases that mix both styles, sometimes in the same folder. You open a
.razorfile, find no@codeblock, and wonder where the logic went: it's in the.razor.csfile collapsed underneath it. The opposite surprise is a code-behind file and an@codeblock in the same component, splitting one class across two places. If you join such a project, check the file tree before assuming a component has no logic, and follow whichever style the folder you're in already uses.
State, data binding and events
Component state is just private fields. Change a field in an event handler and Blazor re-renders the component:
@* ReadingGoal.razor *@
@page "/goal"
@rendermode InteractiveAuto
<h1>Reading goal</h1>
<label>
Books this year:
<input type="number" @bind="goal" @bind:event="oninput" />
</label>
<p>@read of @goal read (@Percent%)</p>
<button @onclick="MarkRead" disabled="@(read >= goal)">I finished a book</button>
@code {
private int goal = 12;
private int read;
private int Percent => goal == 0 ? 0 : read * 100 / goal;
private void MarkRead() => read++;
}
What's going on:
@onclick="MarkRead"attaches a C# method to a DOM event. After the handler runs, Blazor callsStateHasChangedfor you and re-renders. Async handlers work too: Blazor re-renders when the method first awaits and again when it completes.@bind="goal"is two-way binding: the input showsgoal, and typing updatesgoal, converting the string to anintfor you. By default it updates ononchange(when the input loses focus);@bind:event="oninput"makes it update on every keystroke.@bind:after="SomeMethod"runs code after the value is updated, which is the clean way to react to a change without writing the handler yourself.Percentis computed, not stored. Derived values belong in a property, not in a second field you have to keep in sync.
For components, binding uses @bind-{Parameter}. The form inputs in Part 2 use @bind-Value.
Lists and @key
@* BookList.razor *@
@if (Books.Count == 0)
{
<p>No books yet.</p>
}
else
{
<ul>
@foreach (var book in Books)
{
<li @key="book.Id">@book.Title (@book.Year)</li>
}
</ul>
}
@code {
[Parameter] public IReadOnlyList<Book> Books { get; set; } = [];
}
@key tells Blazor's diffing which element belongs to which item. Without it, Blazor matches list items by position, so inserting at the top or reordering can attach the wrong element (and the wrong child component state) to the wrong item. Use a stable id, never the loop index.
Routing and navigation
Any component with an @page directive is a page. Route parameters map to [Parameter] properties, with optional constraints like :int:
@* BookDetails.razor *@
@page "/books/{Id:int}"
@inject IBookService Books
@inject NavigationManager Nav
@if (book is null)
{
<p>Loading…</p>
}
else
{
<h1>@book.Title</h1>
<p>@book.Author, @book.Year</p>
<button @onclick='() => Nav.NavigateTo("/shelf")'>Back to the shelf</button>
}
@code {
[Parameter] public int Id { get; set; }
private Book? book;
// Runs on first render AND whenever the route parameter changes (/books/1 -> /books/2)
protected override async Task OnParametersSetAsync()
{
book = null;
book = await Books.GetBookAsync(Id);
}
}
NavigationManager.NavigateTo navigates in code. For menus, NavLink renders an <a> that gets an active class when its URL matches:
<nav>
<NavLink href="" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="shelf">Shelf</NavLink>
<NavLink href="goal">Reading goal</NavLink>
</nav>
Pages render inside a layout (MainLayout.razor in the template), which holds the shared chrome: header, nav and footer. The layout renders the page where it writes @Body.
The component lifecycle
The methods you'll actually override, in order:
| Method | When it runs | Use it for |
|---|---|---|
OnInitialized{Async} | Once, when the component is first created | Loading data that doesn't depend on changing parameters |
OnParametersSet{Async} | After initialization, and every time the parent passes new parameters | Reacting to parameter changes, like a new route Id |
OnAfterRender{Async}(bool firstRender) | After every render, once the DOM is updated | JavaScript interop, because the elements exist now |
Dispose / DisposeAsync | When the component is removed | Unsubscribing from events, disposing timers |
BookDetails above loads in OnParametersSetAsync, not OnInitializedAsync, on purpose. Navigating from /books/1 to /books/2 reuses the same component instance, so OnInitializedAsync doesn't run again. This is one of the most common Blazor bugs.
One more thing that surprises everyone: with prerendering (on by default for interactive components), OnInitializedAsync runs twice, once on the server to produce the initial HTML and again when the component becomes interactive. Part 3 shows how to persist the first result so you don't call your API twice.
Render modes
This is the biggest change in modern Blazor, and the one to understand first:
| Render mode | Where it runs | Interactive? | Good for |
|---|---|---|---|
| Static SSR (default) | Server; sends plain HTML | No (forms post back; enhanced navigation makes it feel smooth) | Content pages, marketing pages, simple forms |
| Interactive Server | Server; UI events and updates over a SignalR connection (a "circuit") | Yes | Internal apps, fast start-up, keeping code and data on the server |
| Interactive WebAssembly | In the browser on .NET WebAssembly | Yes | Offline-capable or heavy client-side UI, low server load |
| Interactive Auto | Server first, then WebAssembly once the runtime has downloaded and been cached | Yes | Fast first load and client-side execution later |
You set it per component (or per page) with a directive, as in the examples above:
@rendermode InteractiveServer
Or globally, by putting a render mode on the Routes component in App.razor. The template's Program.cs registers whichever modes you chose when you created the project:
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(BookClub.Client._Imports).Assembly);
The rule of thumb from the docs: start with static SSR, and add interactivity only to the components that need it. In a project created with Auto or WebAssembly interactivity, components that may run in the browser live in the .Client project, because that's the code that gets shipped to it.
Component libraries
Most teams don't hand-build every table and date picker. The popular libraries are MudBlazor (Material Design), Radzen, Fluent UI Blazor (Microsoft's, Fluent design) and Syncfusion or Telerik (commercial). They're regular components:
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="AddToShelf">
Add to shelf
</MudButton>
@code {
[Parameter] public EventCallback AddToShelf { get; set; }
}
Pick one and let it own the look of the app. Each library has its own styling system and expects to be in charge.
In the wild: teams often pair a component library with Tailwind CSS: the library brings ready-made controls, and Tailwind brings fast layout. The trade-off is specificity. The library's own styles can outrank your utility classes, so a tweak sometimes needs more force than you'd expect. The standard advice is one primary styling approach, the library's theme or utilities on plain markup, with CSS isolation (
.razor.css) for component-specific tweaks. If a project uses both, it helps to agree which one owns what, and write it down.
Check yourself: questions and answers
1. What is Blazor?
A .NET framework for building web UI with C# and Razor components. Components can render on the server as static HTML, run interactively on the server over SignalR, or run in the browser on WebAssembly.
2. What's a component, and how do parent and child communicate?
A .razor file with markup and C#. Parents pass data down through [Parameter] properties; children notify parents through EventCallback parameters. RenderFragment parameters let a parent pass markup.
3. Why use EventCallback instead of Action?
EventCallback automatically re-renders the component that owns the handler after it runs, supports async handlers, and is null-safe to invoke. A plain delegate would need a manual StateHasChanged.
4. What does @bind do, and when does it update?
Two-way binding between an element's value and a field, with type conversion. It updates on onchange by default; @bind:event="oninput" updates on every keystroke, and @bind:after runs code after the update.
5. Why use @key in a list?
So Blazor matches elements and child components to items by identity instead of position. Without it, inserting or reordering can keep the wrong DOM state or component state with the wrong item.
6. OnInitializedAsync vs OnParametersSetAsync?
OnInitializedAsync runs once per component instance. OnParametersSetAsync runs after it and on every parameter change. Navigating between /books/1 and /books/2 reuses the instance, so load route-dependent data in OnParametersSetAsync.
7. Why might OnInitializedAsync run twice?
Prerendering. The component runs once on the server to produce HTML, then again when it becomes interactive. Persist the prerendered state, or disable prerendering for that component.
8. Name the render modes and when you'd use each.
Static SSR for non-interactive pages; Interactive Server for internal apps that need fast start-up and keep code on the server; Interactive WebAssembly to run in the browser and offload the server; Interactive Auto for a fast first load that switches to WebAssembly once it's cached.
9. What's the downside of Interactive Server?
Every interaction is a round trip over a persistent connection, so latency matters, each user holds server memory for their circuit, and a dropped connection interrupts the UI until it reconnects.
10. How does CSS isolation work?
A Component.razor.css file next to the component is bundled at build time, with its selectors rewritten to include a unique attribute that Blazor also adds to the component's elements, so the styles can't leak out.
11. What's the difference between a page and a component?
Nothing structural: a page is a component with an @page directive, so the router can navigate to it. By convention, pages live in a Pages folder and own the screen's data and actions, while reusable components take parameters, raise EventCallbacks and don't know where they're used.
12. @code block or code-behind?
Both compile to the same class. A code-behind file is a partial class in Component.razor.cs with the same name and the same namespace as the .razor file, and @inject becomes an [Inject] property. Choose per team convention: single file for small components, code-behind for logic-heavy ones. Older codebases may use a base class with @inherits, where members the markup uses must be protected.
Go deeper
- C# Fundamentals That Trip People Up and Modern C# Features: the C# that Razor code leans on (records, pattern matching, nullable types)
- The React Learning Path, if you want the same concepts in the other stack
Next: Part 2, building real features.
Further reading
- Microsoft Learn, ASP.NET Core Blazor and Razor components
- Microsoft Learn, Data binding and Event handling
- Microsoft Learn, Routing and Component lifecycle
- Microsoft Learn, Render modes and Project structure
- Microsoft Learn, CSS isolation
- Microsoft Learn, Migrate from ASP.NET Core 7.0 to 8.0, which covers moving a hosted WebAssembly app to a Blazor Web App
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.