›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Blazor Learning Path

Blazor Learning Path, Part 2: Building Real Features

October 31, 2026 · 15 min read

Blazor, C#, .NET, Razor, Interview Prep, State Management

Part 1 covered components, binding and render modes. This part is where a Blazor app turns into a real product: forms, services, data from APIs, shared state, permissions, two languages, and the occasional JavaScript library. It's also where real projects most often make their own trade-offs, so look out for the In the wild notes.

All the code compiles on .NET 10, in the same book club example app.

Forms and validation

Blazor's form components wire validation, binding and submission together. Start with a model and DataAnnotations:

using System.ComponentModel.DataAnnotations;

public class NewBook
{
    [Required, StringLength(120)]
    public string Title { get; set; } = "";

    [Required]
    public string Author { get; set; } = "";

    [Range(1450, 2100, ErrorMessage = "Enter a real publication year.")]
    public int Year { get; set; } = DateTime.Today.Year;
}

Then an EditForm:

@page "/books/new"
@rendermode InteractiveAuto

<EditForm Model="book" OnValidSubmit="SaveAsync" FormName="add-book">
    <DataAnnotationsValidator />
    <ValidationSummary />

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

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

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

    <button type="submit">Add book</button>
</EditForm>

@if (saved)
{
    <p>Saved.</p>
}

@code {
    private NewBook book = new();
    private bool saved;

    private async Task SaveAsync()
    {
        await Task.Delay(100); // call your API here
        saved = true;
        book = new();
    }
}
  • EditForm creates an EditContext that tracks which fields changed and which are invalid, and cascades it to everything inside.
  • DataAnnotationsValidator runs the attributes. OnValidSubmit only fires when the model is valid; use OnSubmit if you want to handle both cases yourself.
  • InputText, InputNumber, InputDate, InputSelect, InputCheckbox bind with @bind-Value and add valid/invalid CSS classes automatically.
  • FormName is required when the form is submitted under static SSR (along with [SupplyParameterFromForm] on the model). It's harmless in interactive mode, and adding it means the form keeps working if you change the render mode later.

When rules get complex: FluentValidation

DataAnnotations are fine for "required" and "max length". Cross-field rules ("title and author look swapped") read better in FluentValidation:

using FluentValidation;

public class NewBookValidator : AbstractValidator<NewBook>
{
    public NewBookValidator()
    {
        RuleFor(b => b.Title).NotEmpty().MaximumLength(120);
        RuleFor(b => b.Author).NotEmpty();
        RuleFor(b => b.Year)
            .InclusiveBetween(1450, DateTime.Today.Year + 1)
            .WithMessage("Enter a real publication year.");
        // Rules that DataAnnotations can't express cleanly:
        RuleFor(b => b.Title)
            .Must((book, title) => !string.Equals(title, book.Author, StringComparison.OrdinalIgnoreCase))
            .WithMessage("Title and author look swapped.");
    }
}

FluentValidation's own docs say it "does not provide integration with Blazor out of the box", and point to community packages (the once-popular Blazored.FluentValidation is now archived). The integration is small enough to write yourself, and writing it teaches you how EditContext works:

using FluentValidation;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

// Plugs a FluentValidation validator into EditForm, the same way <DataAnnotationsValidator /> does.
public sealed class FluentValidator<TModel> : ComponentBase, IDisposable
{
    [CascadingParameter] public EditContext EditContext { get; set; } = default!;
    [Parameter, EditorRequired] public IValidator<TModel> Validator { get; set; } = default!;

    private ValidationMessageStore messages = default!;

    protected override void OnInitialized()
    {
        messages = new ValidationMessageStore(EditContext);
        EditContext.OnValidationRequested += ValidateAll;  // on submit
        EditContext.OnFieldChanged += ValidateField;       // as the user edits
    }

    private void ValidateAll(object? sender, ValidationRequestedEventArgs e)
    {
        messages.Clear();
        foreach (var error in Validator.Validate((TModel)EditContext.Model).Errors)
            messages.Add(EditContext.Field(error.PropertyName), error.ErrorMessage);
        EditContext.NotifyValidationStateChanged();
    }

    private void ValidateField(object? sender, FieldChangedEventArgs e)
    {
        var field = e.FieldIdentifier;
        messages.Clear(field);
        foreach (var error in Validator.Validate((TModel)EditContext.Model).Errors)
            if (error.PropertyName == field.FieldName)
                messages.Add(field, error.ErrorMessage);
        EditContext.NotifyValidationStateChanged();
    }

    public void Dispose()
    {
        EditContext.OnValidationRequested -= ValidateAll;
        EditContext.OnFieldChanged -= ValidateField;
    }
}

Use it in place of <DataAnnotationsValidator />: <FluentValidator TModel="NewBook" Validator="validator" />. This version handles top-level properties only; nested objects need the property paths mapped, which is what the community packages do.

The rule that matters more than the library: client-side validation is for the user's convenience; server-side validation is for correctness. Anything that reaches your API must be validated there too, because a request doesn't have to come from your UI.

In the wild: teams often start with validation in two places: checks in the Blazor component for quick feedback, and separate checks in the API. It's fast to build, but two sets of rules tend to drift apart over time. The standard approach is to put the model and its validator in a shared project that both the client and the server reference, run it in the form for instant feedback, and run the same validator in the API. One set of rules, enforced twice.

Dependency injection, and what Scoped means here

Services are registered in Program.cs and injected with @inject (or constructor injection in a code-behind class). The lifetimes don't behave quite like they do in a normal ASP.NET Core app:

LifetimeInteractive ServerWebAssembly
SingletonOne instance for the whole server: shared by every userOne instance for this browser tab
ScopedOne instance per circuit, which lasts as long as the user's connection, across many page navigationsNo real scopes: behaves like a singleton
TransientNew instance every time it's injectedSame

The consequences worth knowing:

  • Never put user state in a singleton on the server. Every user would see it.
  • Scoped is "per user session" on the server, not "per request". A scoped DbContext lives for the whole circuit, which is why Microsoft's EF Core guidance for Blazor uses IDbContextFactory and short-lived contexts instead.
  • Don't inject disposable transient services. The container holds on to them until the circuit (or the app) ends, so they leak. If a component needs a service that lives exactly as long as the component, inherit OwningComponentBase.

Calling APIs: typed HttpClients

The standard pattern is one typed client per external API, created through IHttpClientFactory, with settings bound from configuration through the options pattern:

using Microsoft.Extensions.Options;

public sealed class BooksApiOptions
{
    public const string Section = "BooksApi";
    public string BaseUrl { get; set; } = "";
    public int TimeoutSeconds { get; set; } = 30;
}

// A typed client: one class per external API, HttpClient injected and pre-configured.
public sealed class BooksApiClient(HttpClient http)
{
    public async Task<IReadOnlyList<Book>> SearchAsync(string term, CancellationToken ct = default) =>
        await http.GetFromJsonAsync<List<Book>>($"search?q={Uri.EscapeDataString(term)}", ct) ?? [];
}

public static class BooksApiRegistration
{
    public static IServiceCollection AddBooksApi(this IServiceCollection services, IConfiguration config)
    {
        services.Configure<BooksApiOptions>(config.GetSection(BooksApiOptions.Section));

        services.AddHttpClient<BooksApiClient>((sp, http) =>
        {
            var options = sp.GetRequiredService<IOptions<BooksApiOptions>>().Value;
            http.BaseAddress = new Uri(options.BaseUrl);
            http.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
        });

        return services;
    }
}

The factory manages the underlying connections (no socket exhaustion from new HttpClient() per call), the client class gives the rest of the app a small, testable surface (SearchAsync, not URLs), and the options class keeps configuration typed. Resilience (retries, timeouts, circuit breakers) plugs in at the same registration; my cloud resilience post covers that stack.

In the WebAssembly client, the template registers a plain HttpClient pointing at your own server, and the same typed-client idea applies to calls to your backend.

Sharing state between components

From simplest to heaviest:

1. Parameters and callbacks (Part 1). Parent owns the state, children receive it. Always the first choice.

2. Cascading values for things many components read, like a theme or the current club:

@* Wrap part of the tree *@
<CascadingValue Value="theme">
    @ChildContent
</CascadingValue>

@code {
    [Parameter] public RenderFragment? ChildContent { get; set; }
    private readonly Theme theme = new("Night reading", IsDark: true);
}
@* Any descendant can receive it *@
<button class="@(Theme?.IsDark == true ? "btn-dark" : "btn-light")">@ChildContent</button>

@code {
    [CascadingParameter] public Theme? Theme { get; set; }
    [Parameter] public RenderFragment? ChildContent { get; set; }
}

You can also register a root-level cascading value for the whole app in Program.cs with builder.Services.AddCascadingValue(sp => new Theme("Night reading", IsDark: true));.

3. A state container service when unrelated components need the same changing data:

// A plain service that holds shared state and tells subscribers when it changes.
public sealed class ReadingListState
{
    private readonly List<Book> books = [];

    public IReadOnlyList<Book> Books => books;
    public event Action? Changed;

    public void Add(Book book)
    {
        books.Add(book);
        Changed?.Invoke();
    }
}
@implements IDisposable
@inject ReadingListState State

<span class="badge">@State.Books.Count to read</span>

@code {
    protected override void OnInitialized() => State.Changed += OnStateChanged;

    // The event can fire from any thread, so marshal back to the renderer.
    private void OnStateChanged() => InvokeAsync(StateHasChanged);

    public void Dispose() => State.Changed -= OnStateChanged;
}

Register it as scoped (per user on the server, per tab in WebAssembly), and always unsubscribe in Dispose, or the service keeps every component that ever subscribed alive.

4. A Flux-style store such as Fluxor: immutable state, actions, reducers, and components that subscribe:

using Fluxor;

[FeatureState]
public sealed record ShelfState(IReadOnlyList<Book> Books)
{
    private ShelfState() : this([]) { }
}

public sealed record AddBookAction(Book Book);

public static class ShelfReducers
{
    [ReducerMethod]
    public static ShelfState OnAddBook(ShelfState state, AddBookAction action) =>
        state with { Books = [.. state.Books, action.Book] };
}
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject IState<ShelfState> Shelf
@inject IDispatcher Dispatcher

<p>@Shelf.Value.Books.Count books on the shelf</p>
<button @onclick="AddSample">Add a book</button>

@code {
    private void AddSample() =>
        Dispatcher.Dispatch(new AddBookAction(new Book(42, "Piranesi", "Susanna Clarke", 2020)));
}

It gives you one predictable flow for every change and good tooling for debugging, at the cost of a file or three per feature. That trade is worth it for the slices many components share; for state only one page reads, a private field is enough.

Authentication and role-based UI

Blazor uses ASP.NET Core's normal authentication; the UI side is about showing the right things and protecting pages:

@page "/admin"
@attribute [Authorize(Roles = "Organizer")]

<h1>Club admin</h1>
<p>Only organizers can open this page.</p>
<AuthorizeView Roles="Organizer">
    <Authorized>
        <button>Schedule next meeting</button>
    </Authorized>
    <NotAuthorized>
        <p>Ask an organizer to schedule the next meeting.</p>
    </NotAuthorized>
</AuthorizeView>

<AuthorizeView>
    <Authorized>Signed in as @context.User.Identity?.Name</Authorized>
</AuthorizeView>

Better still, give the rule a name with a policy, so the UI and the API check the same thing:

builder.Services.AddAuthorizationCore(options =>
{
    // One named rule, used by the UI and (registered the same way) by the API.
    options.AddPolicy("CanScheduleMeetings", policy =>
        policy.RequireRole("Organizer").RequireClaim("club_id"));
});
<AuthorizeView Policy="CanScheduleMeetings">
    <Authorized>
        <button>Schedule next meeting</button>
    </Authorized>
</AuthorizeView>

AddCascadingAuthenticationState() in Program.cs makes the current user available to all of this.

Hiding a button is not security. In WebAssembly, the user has your app's code and can call your API directly. The server must enforce the same policy on every endpoint (RequireAuthorization("CanScheduleMeetings")).

Localization: English and French

Blazor uses .NET's standard localization: .resx resource files and IStringLocalizer<T>.

// SharedResource.cs: a marker class. IStringLocalizer<SharedResource> looks up
// Resources/SharedResource.resx (English) and Resources/SharedResource.fr.resx (French).
public class SharedResource { }
<!-- Resources/SharedResource.resx -->
<data name="Welcome" xml:space="preserve"><value>Welcome to the book club</value></data>
<data name="BooksRead" xml:space="preserve"><value>{0} books read this year</value></data>

<!-- Resources/SharedResource.fr.resx -->
<data name="Welcome" xml:space="preserve"><value>Bienvenue au club de lecture</value></data>
<data name="BooksRead" xml:space="preserve"><value>{0} livres lus cette année</value></data>
@using Microsoft.Extensions.Localization
@inject IStringLocalizer<SharedResource> L

<h1>@L["Welcome"]</h1>
<p>@L["BooksRead", booksRead]</p>

@code {
    private int booksRead = 7;
}

Register it with builder.Services.AddLocalization();. How the current culture is chosen depends on the render mode: on the server, request localization middleware (usually driven by a culture cookie); in WebAssembly, you set CultureInfo.DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture before the app starts. The globalization doc in Further reading walks through both, including a culture picker.

In the wild: .resx for English and French is the standard, and it holds up well. The gotchas are human, not technical. Keys named after the English text ("SaveChanges") stop making sense when the text changes, so name keys after their purpose ("BookForm_Submit"). French capitalization differs from English: titles and buttons use sentence case ("Ajouter un livre", not "Ajouter Un Livre"), and French text is often noticeably longer than the English, so leave room in buttons and table headers. Use placeholders ({0}) rather than concatenating sentence fragments, because word order differs between languages.

JavaScript interop, the recommended way

Sometimes a JavaScript library is the right tool: charts, maps, rich-text editors. Microsoft's guidance is JS modules collocated with the component, imported on demand, rather than global functions in a <script> tag. And keep the boundary clean: C# owns the data and the logic; JavaScript only draws.

// BooksPerYearChart.razor.js, collocated with the component.
// Drawing only: the data arrives already shaped by C#.
// Chart.js itself is self-hosted under wwwroot/lib and loaded once in App.razor.
export function drawBarChart(canvas, labels, values, title) {
  return new Chart(canvas, {
    type: "bar",
    data: { labels, datasets: [{ label: title, data: values }] },
    options: { animation: false },
  });
}

export function destroyChart(chart) {
  chart?.destroy();
}
@* BooksPerYearChart.razor *@
@implements IAsyncDisposable
@inject IJSRuntime JS

<canvas @ref="canvas"></canvas>

@code {
    [Parameter, EditorRequired] public IReadOnlyList<Book> Books { get; set; } = [];

    private ElementReference canvas;
    private IJSObjectReference? module;
    private IJSObjectReference? chart;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender) return; // the <canvas> only exists after the first render

        // C# owns the data logic: grouping, sorting, labels.
        var perYear = Books
            .GroupBy(b => b.Year)
            .OrderBy(g => g.Key)
            .Select(g => (Year: g.Key.ToString(), Count: g.Count()))
            .ToList();

        module = await JS.InvokeAsync<IJSObjectReference>(
            "import", "./Components/BooksPerYearChart.razor.js");
        chart = await module.InvokeAsync<IJSObjectReference>(
            "drawBarChart", canvas,
            perYear.Select(p => p.Year).ToArray(),
            perYear.Select(p => p.Count).ToArray(),
            "Books per year");
    }

    public async ValueTask DisposeAsync()
    {
        try
        {
            if (module is not null)
            {
                await module.InvokeVoidAsync("destroyChart", chart);
                await module.DisposeAsync();
            }
        }
        catch (JSDisconnectedException)
        {
            // Interactive Server: the circuit is already gone, nothing to clean up.
        }
    }
}

Why each piece is there:

  • OnAfterRenderAsync(firstRender): JS can only touch elements after they exist in the DOM. It also doesn't run during prerendering, so JS calls are safe here.
  • ElementReference passes the actual <canvas> to JavaScript, with no ids or querySelector needed.
  • The module path is the component's path in the project: a component at Components/BooksPerYearChart.razor has its module served at Components/BooksPerYearChart.razor.js.
  • Disposal destroys the chart and releases the module. On Interactive Server, the circuit may already be gone, hence the JSDisconnectedException catch, which Microsoft's docs recommend.
  • Testing: the grouping logic is plain C#, so it can be unit-tested without a browser.

Self-host the library. Put the script in wwwroot/lib, pinned to a version and served with your app, rather than loading it from a public CDN. Your app then works on networks that block third-party hosts, and an upgrade is a deliberate change instead of a surprise.

MarkupString, briefly

Blazor HTML-encodes everything you render, so @someString can never inject markup. When you genuinely need to render HTML, you cast to MarkupString:

<div class="blurb">@((MarkupString)BlurbHtml)</div>

@code {
    // Only for HTML you trust, like copy from your own CMS. Never raw user input.
    [Parameter] public string BlurbHtml { get; set; } = "";
}

That cast switches off Blazor's protection, so treat every MarkupString like a security review item. Part 3 shows how to handle HTML you don't control.

Check yourself: questions and answers

1. What does EditForm give you over a plain <form>?

An EditContext that tracks field state and validation messages, validator components (DataAnnotationsValidator or a custom one), input components that bind and show validity, and OnValidSubmit/OnInvalidSubmit callbacks.

2. What's different about Scoped services in Blazor?

On the server, a scope lasts for the user's circuit, across many navigations, not one HTTP request. In WebAssembly there are no real scopes, so scoped behaves like singleton. Singletons on the server are shared by all users.

3. Why use IHttpClientFactory and typed clients?

The factory pools and recycles handlers, avoiding socket exhaustion and stale DNS; typed clients give the app a small, testable API surface and a single place to configure the base address, headers and resilience.

4. How do you share state between components that aren't related?

A scoped state container service with a change event that components subscribe to (calling InvokeAsync(StateHasChanged) and unsubscribing on dispose), or a store such as Fluxor when the shared state is large and complex. Cascading values suit read-mostly data down a subtree.

5. When would you use Fluxor, and when wouldn't you?

When many components share complex, frequently changing state and you want a single predictable update path. Not for local UI state, where it adds actions, reducers and indirection for no benefit.

6. Is AuthorizeView enough to secure a feature?

No. It only controls what's rendered. The API must enforce the same authorization, ideally the same named policy, because WebAssembly code runs on the user's machine and requests can be made without your UI.

7. Roles vs policies?

Roles are a single check on the user's role claims. Policies name a rule that can combine roles, claims and custom requirements, so the rule is defined once and used by both the UI and the API.

8. How does localization work in Blazor?

.resx files per culture, read through IStringLocalizer<T>. The culture comes from request localization (usually a cookie) on the server, or is set on CultureInfo before startup in WebAssembly.

9. When can you call JavaScript from a component?

In OnAfterRenderAsync, after the elements exist and not during prerendering. Prefer collocated JS modules imported with IJSRuntime, and dispose module references, catching JSDisconnectedException on Interactive Server.

10. What's the risk with MarkupString?

It renders the string as raw HTML, bypassing Blazor's encoding. With untrusted input that's a cross-site scripting hole, so only use it for trusted content or sanitize first.

Go deeper

  • Testing in .NET, on testing the services behind your components
  • Entity Framework Core: Performance and Production Gotchas, relevant to that long-lived scoped DbContext
  • Cloud Resilience Patterns, for the retry, timeout and circuit breaker stack behind a typed client
  • React Learning Path, Part 2, on the same state questions in React

Next: Part 3, advanced Blazor.

Further reading

  • Microsoft Learn, Forms overview and Forms validation
  • FluentValidation, Blazor
  • Microsoft Learn, Blazor dependency injection
  • Microsoft Learn, Call a web API from Blazor and IHttpClientFactory
  • Microsoft Learn, State management and Cascading values and parameters
  • Fluxor, GitHub repository and docs
  • Microsoft Learn, Blazor authentication and authorization
  • Microsoft Learn, Globalization and localization
  • Microsoft Learn, JavaScript interop and JavaScript location
  • Microsoft, eShop reference application
← Previous

Cloud Structure and Migration Patterns and the GoF Patterns Inside Them

Next →

Why One Zone's Power Cut Reached a Whole Region: Google's Report

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.