Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 41 ยท Projects and Practice

Project: Expense Tracker with Forms and Validation

Build an expense tracker in Blazor with an EditForm, data annotations, a service layer, an HTTP-backed repository and totals by category, with runnable domain logic.

The second project is a classic business app: an expense tracker. Users enter an expense (date, description, amount, category), the app validates it, stores it and shows totals per category. It exercises the pieces of Blazor you will use most in real work: EditForm with data annotations, a repository behind an interface, dependency injection, an API client and computed summaries.

As before, the Razor code is real and read-only because Blazor cannot run here, and the logic is runnable: validation (using the real System.ComponentModel.DataAnnotations validator, which is plain .NET), the repository and the report. That is the same code your components will call.

The plan

Layer Piece Responsibility
UI Expenses.razor, ExpenseForm.razor, CategoryTotals.razor Show the list, collect input, show totals
Service ExpenseService Rules: validate, add, summarize
Data IExpenseRepository Store and load (in memory first, API or database later)
Model Expense Data plus validation attributes

Putting storage behind an interface is the key decision: the same service works with an in-memory list in a demo, a database on the server, or HttpClient calls in WebAssembly (see Calling APIs from Blazor with HttpClient).

Step 1: the model and its validation

Blazor's EditForm validates with DataAnnotationsValidator, which runs the attributes on your model. The same attributes can be checked in plain C# with Validator.TryValidateObject, so you can test them without a UI.

C# Model with data annotations, validated in plain C#

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 form, each message is shown by <ValidationMessage For="() => model.Amount" /> next to its field, and <ValidationSummary /> lists them all.

Step 2: repository and service

C# Repository interface, in-memory implementation and service

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.

Register the service and a repository in Program.cs. Swapping the implementation later changes one line:

C#
builder.Services.AddSingleton<IExpenseRepository, InMemoryExpenseRepository>();   // demo
// builder.Services.AddScoped<IExpenseRepository, EfExpenseRepository>();         // database
builder.Services.AddScoped<ExpenseService>();

The in-memory repository is a singleton because it must outlive a single circuit's scope, otherwise each user would start with an empty list. A database-backed repository is usually scoped (see Service Lifetimes and Scopes).

Step 3: the form component

RAZOR
@inject ExpenseService Service

<EditForm Model="model" OnValidSubmit="Save" FormName="new-expense">
    <DataAnnotationsValidator />
    <ValidationSummary />

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

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

    <label>Category
        <InputSelect @bind-Value="model.Category">
            <option value="">Choose...</option>
            @foreach (var c in categories) { <option>@c</option> }
        </InputSelect>
    </label>
    <ValidationMessage For="() => model.Category" />

    <label>Date <InputDate @bind-Value="model.Date" /></label>

    <button type="submit" disabled="@saving">@(saving ? "Saving..." : "Add expense")</button>
</EditForm>

@code {
    private static readonly string[] categories = ["Food", "Travel", "Fun", "Home"];
    private ExpenseInput model = new() { Date = DateOnly.FromDateTime(DateTime.Today) };
    private bool saving;

    [Parameter] public EventCallback OnSaved { get; set; }

    private async Task Save()
    {
        saving = true;
        try
        {
            await Service.AddAsync(model.ToExpense());
            model = new() { Date = DateOnly.FromDateTime(DateTime.Today) };
            await OnSaved.InvokeAsync();
        }
        finally { saving = false; }
    }
}

Points worth noticing: the submit button is disabled while saving (no double submits, see Form Patterns and Submit State); a successful save replaces the model so the form clears and old validation messages disappear; and the form raises OnSaved to let the parent reload the list.

Step 4: list and totals

RAZOR
@page "/expenses"
@inject ExpenseService Service

<ExpenseForm OnSaved="Load" />

<table>
    <thead><tr><th>Date</th><th>What</th><th>Category</th><th>Amount</th></tr></thead>
    <tbody>
        @foreach (var e in items)
        {
            <tr @key="e.Id">
                <td>@e.Date.ToString("yyyy-MM-dd")</td>
                <td>@e.Description</td>
                <td>@e.Category</td>
                <td class="num">@e.Amount.ToString("C")</td>
            </tr>
        }
    </tbody>
</table>

<CategoryTotals Totals="totals" />

@code {
    private IReadOnlyList<Expense> items = [];
    private List<(string Category, decimal Total, double Share)> totals = [];

    protected override Task OnInitializedAsync() => Load();

    private async Task Load()
    {
        items = await Service.GetAllAsync();
        totals = await Service.TotalsByCategoryAsync();
    }
}

Format money with ToString("C") so the user's culture is respected, and keep amounts as decimal, never double, to avoid rounding errors.

Ideas to extend it

  • Edit and delete rows (a modal using a child component and EventCallbacks).
  • A date-range filter driven by query strings, so a filtered view can be shared as a link.
  • Move the repository to EF Core with SQLite, or to a minimal API reached with a typed HttpClient.
  • Add authentication so each person sees only their own expenses, and enforce that in the data layer.
  • Export to CSV through a small JavaScript function (see JS Modules and Calling .NET from JavaScript).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which component runs the attributes such as [Required] and [Range] inside an EditForm?

    DataAnnotationsValidator validates the model's attributes; ValidationMessage and ValidationSummary only display the results.
  2. 2. Why hide storage behind IExpenseRepository?

    The service depends on the abstraction, so implementations can be swapped and tested separately.
  3. 3. Which type should store money amounts?

    decimal avoids binary floating-point rounding surprises in financial values.
  4. 4. Why replace the model object after a successful save?

    A fresh model gives an empty form with no old messages.

Summary

  • Annotate the model, let DataAnnotationsValidator check it and show messages next to each field.
  • Keep rules in a service and storage behind an interface so you can swap implementations.
  • Disable the submit button while saving and clear the form by replacing the model.
  • Use decimal for money and culture-aware formatting for display.
  • The same domain code runs and tests in plain C#, which is why the logic here was runnable.

Next: Blazor Practice Set and Next Steps