SharpRuneOpen playground

Expense form with validation

Add expenses through a validated EditForm and see totals per category, computed with LINQ in a summary component.

  • Blazor
  • 10 project files
  • EditForm
  • DataAnnotations
  • LINQ
  • scoped CSS

A Blazor WebAssembly project. The playground compiles the Razor components and C# in your browser and opens the running app in its preview, on .NET 10, 11 or 9. In the SharpRune app, open it from the Examples tab and tap Run. On a computer, save the files below and run dotnet run with the matching .NET SDK.

Expenses.csproj

Expenses.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>Expenses</AssemblyName>
    <RootNamespace>Expenses</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>

Program.cs

Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Expenses;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

await builder.Build().RunAsync();

App.razor

App.razor
@* The root component: a header and the Router. *@
<header class="bar">
    <span class="brand">Expenses</span>
    <span class="tag">EditForm · LINQ totals</span>
</header>

<main>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <h1>Not found</h1>
            <p>There is no page at this address.</p>
        </NotFound>
    </Router>
</main>

_Imports.razor

_Imports.razor
@using System.Globalization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Expenses
@using Expenses.Components
@using Expenses.Models

Components/ExpenseSummary.razor

Components/ExpenseSummary.razor
@* Receives the expenses as a parameter and computes totals per category with LINQ. *@

<section class="summary">
    <h2>Totals by category</h2>

    @if (totals.Count == 0)
    {
        <p class="empty">Add an expense to see totals.</p>
    }
    else
    {
        <ul>
            @foreach (var total in totals)
            {
                <li>
                    <span class="name">@total.Category <small>× @total.Count</small></span>
                    <span class="value">@Money.Format(total.Amount)</span>
                    <span class="meter"><span style="width: @Percent(total.Amount)%"></span></span>
                </li>
            }
        </ul>
        <p class="grand">Total: <strong>@Money.Format(grandTotal)</strong> in @Expenses.Count expense(s)</p>
    }
</section>

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

    private List<CategoryTotal> totals = [];
    private decimal grandTotal;

    // Runs each time the parent renders and passes the list again.
    protected override void OnParametersSet()
    {
        totals = Expenses
            .GroupBy(expense => expense.Category)
            .Select(group => new CategoryTotal(group.Key, group.Sum(e => e.Amount), group.Count()))
            .OrderByDescending(total => total.Amount)
            .ToList();
        grandTotal = totals.Sum(total => total.Amount);
    }

    // The largest category fills the bar; the others are a share of it.
    private string Percent(decimal amount)
    {
        var largest = totals[0].Amount;
        var percent = largest == 0 ? 0 : amount / largest * 100;
        return percent.ToString("0", CultureInfo.InvariantCulture);
    }

    private sealed record CategoryTotal(string Category, decimal Amount, int Count);
}

Components/ExpenseSummary.razor.css

Components/ExpenseSummary.razor.css
/* Scoped to ExpenseSummary.razor: these rules do not leak into the rest of the app. */
.summary {
    margin: 24px 0 8px;
    padding: 4px 14px 12px;
    border: 1px solid var(--line);
    border-radius: 12px;
}

h2 {
    margin-top: 12px;
}

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 4px 12px;
    padding: 6px 0;
}

.value {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
}

.meter {
    grid-column: 1 / -1;
    height: 8px;
    border-radius: 4px;
    background: rgba(139, 92, 246, 0.15);
    overflow: hidden;
}

.meter span {
    display: block;
    height: 100%;
    background: #8b5cf6;
}

.name small {
    color: #777;
}

.empty, .grand {
    margin: 8px 0 0;
}

Models/Expense.cs

Models/Expense.cs
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace Expenses.Models;

// What the form edits. Nullable properties let the form start empty;
// the attributes decide what counts as complete.
public sealed class ExpenseDraft
{
    [Required(ErrorMessage = "Describe the expense.")]
    [StringLength(60, ErrorMessage = "Keep the description under 60 characters.")]
    public string? Description { get; set; }

    [Range(0.01, 100_000, ErrorMessage = "Enter an amount greater than 0 (up to 100000).")]
    public decimal Amount { get; set; }

    [Required(ErrorMessage = "Choose a category.")]
    public string? Category { get; set; }

    [Required(ErrorMessage = "Choose a date.")]
    public DateOnly? Date { get; set; } = DateOnly.FromDateTime(DateTime.Today);

    // Called only after validation passed, so the null-forgiving operators are safe.
    public Expense ToExpense() => new(Description!.Trim(), Amount, Category!, Date!.Value);
}

// What the list stores: complete and immutable.
public sealed record Expense(string Description, decimal Amount, string Category, DateOnly Date);

public static class Categories
{
    public static readonly string[] All = ["Food", "Transport", "Home", "Fun", "Other"];
}

public static class Money
{
    public static string Format(decimal amount) =>
        "€" + amount.ToString("0.00", CultureInfo.InvariantCulture);
}

Pages/Home.razor

Pages/Home.razor
@page "/"

<PageTitle>Expenses</PageTitle>

<h1>Expenses</h1>

<EditForm Model="draft" OnValidSubmit="Add" class="expense-form">
    <DataAnnotationsValidator />

    <div class="field">
        <label for="description">Description</label>
        <InputText id="description" @bind-Value="draft.Description" placeholder="Lunch with Sam" />
        <ValidationMessage For="() => draft.Description" />
    </div>

    <div class="pair">
        <div class="field">
            <label for="amount">Amount (€)</label>
            <InputNumber id="amount" @bind-Value="draft.Amount" />
            <ValidationMessage For="() => draft.Amount" />
        </div>

        <div class="field">
            <label for="category">Category</label>
            <InputSelect id="category" @bind-Value="draft.Category">
                <option value="">Choose…</option>
                @foreach (var category in Categories.All)
                {
                    <option value="@category">@category</option>
                }
            </InputSelect>
            <ValidationMessage For="() => draft.Category" />
        </div>
    </div>

    <div class="field">
        <label for="date">Date</label>
        <InputDate id="date" @bind-Value="draft.Date" />
        <ValidationMessage For="() => draft.Date" />
    </div>

    <button type="submit" class="primary">Add expense</button>
</EditForm>

@* The summary gets the list as a parameter and re-renders whenever this page does. *@
<ExpenseSummary Expenses="expenses" />

<h2>All expenses</h2>

@if (expenses.Count == 0)
{
    <p class="muted">No expenses yet.</p>
}
else
{
    <ul class="expenses">
        @foreach (var expense in expenses.OrderByDescending(e => e.Date))
        {
            <li>
                <div class="what">
                    <strong>@expense.Description</strong>
                    <span>@expense.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) · @expense.Category</span>
                </div>
                <span class="amount">@Money.Format(expense.Amount)</span>
                <button class="link" @onclick="() => expenses.Remove(expense)" aria-label="Remove @expense.Description">Remove</button>
            </li>
        }
    </ul>
}

@code {
    private ExpenseDraft draft = new();

    private readonly List<Expense> expenses =
    [
        new("Groceries", 42.80m, "Food", new DateOnly(2026, 11, 3)),
        new("Bus pass", 29.00m, "Transport", new DateOnly(2026, 11, 1)),
        new("Pizza night", 18.50m, "Food", new DateOnly(2026, 11, 7))
    ];

    // Runs only when every rule on ExpenseDraft passes.
    private void Add()
    {
        expenses.Add(draft.ToExpense());
        // A new draft gives the EditForm a new EditContext: empty fields, no messages.
        draft = new ExpenseDraft();
    }
}

Pages/Home.razor.css

Pages/Home.razor.css
/* Scoped to Home.razor. ::deep reaches into the Input components' <input> and <select>. */
.field {
    display: flex;
    flex-direction: column;
    gap: 4px;
    margin-bottom: 12px;
}

.field ::deep input,
.field ::deep select {
    width: 100%;
    min-height: 42px;
}

.pair {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0 12px;
}

.expenses {
    list-style: none;
    padding: 0;
    margin: 0;
}

.expenses li {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 0;
    border-bottom: 1px solid var(--line);
}

.what {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
}

.what span {
    color: #777;
    font-size: 0.9rem;
}

.amount {
    font-variant-numeric: tabular-nums;
    font-weight: 600;
}

wwwroot/index.html

wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Expenses</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="Expenses.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

wwwroot/css/app.css

wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
    --danger: #d32f2f;
    --ok: #2e7d32;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

a, button, input, label { touch-action: manipulation; }

select { touch-action: manipulation; }

.bar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px 16px;
    padding: 12px 16px;
    background: #1f1b3a;
    color: #fff;
}

.brand {
    font-weight: 700;
    margin-right: auto;
}

.bar nav {
    display: flex;
    gap: 4px;
}

.bar nav a {
    color: #d9d4ff;
    text-decoration: none;
    padding: 6px 10px;
    border-radius: 8px;
}

.bar nav a.active {
    background: var(--accent);
    color: #fff;
}

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
    box-sizing: border-box;
}

h1 {
    font-size: 1.8rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 24px 0 8px;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

.muted {
    color: #777;
}

.row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]), select, textarea {
    font: inherit;
    color: inherit;
    background: transparent;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    box-sizing: border-box;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

button.link {
    border: none;
    color: var(--accent);
    padding: 4px 6px;
}

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

.tag {
    color: #d9d4ff;
    font-size: 0.9rem;
}

/* Blazor adds modified, valid and invalid to Input components. */
.modified.valid:not([type=checkbox]) {
    border-color: var(--ok);
}

.invalid:not([type=checkbox]) {
    border-color: var(--danger);
}

.validation-message {
    color: var(--danger);
    font-size: 0.9rem;
}