Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 41 ยท Projects and Practice

Project: Build a Task Board in Blazor

Build a Kanban-style task board in Blazor step by step: model and service, state container with change events, reusable components, filtering and the runnable logic.

Time to combine what you learned. In this project you design a task board: tasks live in columns (To do, Doing, Done), you can add tasks, move them forward and filter by text. The project touches components and parameters, event callbacks, a shared state container with change notification, and a service registered with dependency injection.

Blazor cannot run inside this tutorial, so the Razor files are real code to copy into a new Blazor Web App (Interactive Server is simplest), and they are read-only. The domain logic is runnable: the same TaskBoard class that the components use runs below on the site, so you can test the rules before you build any UI. Good Blazor apps keep rules in plain classes like this and keep components thin.

The plan

flowchart TB
    subgraph UI["Components"]
        P["Board.razor (page)"] --> C["Column.razor"]
        C --> K["TaskCard.razor"]
        P --> F["NewTaskForm.razor"]
    end
    P --> S["BoardState (scoped service)"]
    S --> M["TaskBoard (plain C# rules)"]

Components read and call BoardState, which wraps the rules in TaskBoard and raises Changed.

Build order: model and rules first, then the state container, then components from the leaves (TaskCard) up to the page.

Step 1: model and rules

The rules are simple but worth testing: new tasks start in To do, a task moves one column at a time, and Done tasks cannot move further. Running this code is the first milestone.

C# Task board rules (domain model)

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.

Notice that tasks are records: moving a task creates a changed copy with with. Immutable items make change detection simpler, which suits Blazor's rendering.

Step 2: the state container

The board is shared by several components, so wrap it in a scoped service that raises an event on every change (the pattern from State Containers and App State). Here it is as a stand-in you can run, using the TaskBoard idea in a smaller form:

C# State container with Changed event

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.

In the real app, BoardState holds a TaskBoard, forwards its methods, and calls Changed?.Invoke() after each. Register it with builder.Services.AddScoped<BoardState>();.

Step 3: the components

Build from the smallest piece. TaskCard.razor shows one task and reports a click upwards with an EventCallback:

RAZOR
<div class="card">
    <span>@Task.Title</span>
    @if (Task.Status != TaskStatus.Done)
    {
        <button @onclick="() => OnAdvance.InvokeAsync(Task.Id)">Move on</button>
    }
</div>

@code {
    [Parameter, EditorRequired] public BoardTask Task { get; set; } = default!;
    [Parameter] public EventCallback<int> OnAdvance { get; set; }
}

Column.razor renders a title, a count and its cards, using a foreach with @key so that moved cards keep their identity:

RAZOR
<section class="column">
    <h2>@Title <small>(@Tasks.Count())</small></h2>
    @foreach (var task in Tasks)
    {
        <TaskCard @key="task.Id" Task="task" OnAdvance="OnAdvance" />
    }
</section>

@code {
    [Parameter, EditorRequired] public string Title { get; set; } = "";
    [Parameter, EditorRequired] public IEnumerable<BoardTask> Tasks { get; set; } = [];
    [Parameter] public EventCallback<int> OnAdvance { get; set; }
}

NewTaskForm.razor uses EditForm with a model and validation (see EditForm Basics and Validation with Data Annotations) and raises OnAdded with the title.

Board.razor is the page. It injects the state, subscribes in OnInitialized and unsubscribes in Dispose, and owns the search box with @bind:

RAZOR
@page "/board"
@implements IDisposable
@inject BoardState State

<h1>Task board</h1>

<input placeholder="Search..." @bind="search" @bind:event="oninput" />
<NewTaskForm OnAdded="title => State.Add(title)" />

<div class="columns">
    @foreach (var status in Enum.GetValues<TaskStatus>())
    {
        <Column Title="@status.ToString()"
                Tasks="Filter(State.In(status))"
                OnAdvance="State.MoveForward" />
    }
</div>

@code {
    private string search = "";

    protected override void OnInitialized() => State.Changed += Refresh;

    private void Refresh() => InvokeAsync(StateHasChanged);

    private IEnumerable<BoardTask> Filter(IEnumerable<BoardTask> tasks) =>
        string.IsNullOrWhiteSpace(search)
            ? tasks
            : tasks.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));

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

Every concept appears: parameters, event callbacks, @bind, @key, injection, lifecycle and disposal.

Step 4: persistence and polish

Out of the box, the board vanishes on refresh, as State Containers and App State explains. To keep tasks:

  • Back BoardState with a database through a repository interface (Entity Framework Core and SQLite are a good start), or
  • Save to browser localStorage through JS interop (see JavaScript Interop Basics) for a client-side-only app.

Other upgrades to try: drag and drop with @ondrop, a due-date field with validation, per-user boards behind authentication, and a /board/{Id:int} route for several boards (see Route Constraints and Catch-All Routes).

Testing the rules

Because TaskBoard is plain C#, you can test it without a browser. In an xUnit or bUnit project:

C#
[Fact]
public void Done_tasks_cannot_move()
{
    var board = new TaskBoard();
    var t = board.Add("x");
    board.MoveForward(t.Id); board.MoveForward(t.Id); board.MoveForward(t.Id);
    Assert.Equal(TaskStatus.Done, board.In(TaskStatus.Done).Single().Status);
}

bUnit can render the components and click buttons the same way a user would, covering the UI layer on top.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why keep the board rules in a plain C# class instead of inside components?

    Thin components and plain rules classes are easier to test and reason about.
  2. 2. Why does Board.razor unsubscribe from State.Changed in Dispose?

    A long-lived service holding a handler would keep the disposed component in memory.
  3. 3. What is @key on TaskCard for?

    Keys let the diffing algorithm match items correctly when they move or are removed.
  4. 4. How does a TaskCard tell its parent that the user clicked Move on?

    EventCallback is the standard child-to-parent communication, and it triggers re-rendering of the receiver.

Summary

  • Start with plain domain classes and test them; the UI becomes a thin layer on top.
  • A scoped state container with a Changed event lets many components share the board.
  • Leaf components take [Parameter] data and report with EventCallback; the page wires everything together.
  • Use @key in lists, subscribe in OnInitialized, unsubscribe in Dispose.
  • Persist with a database or browser storage, because component state does not survive a refresh.

Next: Project: Expense Tracker with Forms and Validation