SharpRuneOpen playground

Quiz with routes and a timer

A five-question Blazor quiz with a start page, one route per question, a 15-second countdown on a disposed timer, and a results page that reads the score from a shared service.

  • Blazor
  • 11 project files
  • Routing
  • services
  • lifecycle
  • timer

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.

BlazorQuiz.csproj

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

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>BlazorQuiz</AssemblyName>
    <RootNamespace>BlazorQuiz</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 BlazorQuiz;
using BlazorQuiz.Services;

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

// One quiz for the whole app: the question pages write answers, the results page reads the score.
builder.Services.AddSingleton<QuizState>();

await builder.Build().RunAsync();

App.razor

App.razor
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <h1>Not found</h1>
            <p>There is no page at this address.</p>
            <p><a href="">Back to the start</a></p>
        </LayoutView>
    </NotFound>
</Router>

_Imports.razor

_Imports.razor
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using BlazorQuiz
@using BlazorQuiz.Layout
@using BlazorQuiz.Services

Layout/MainLayout.razor

Layout/MainLayout.razor
@inherits LayoutComponentBase

<div class="shell">
    <header>
        <a class="brand" href="">Blazor Quiz</a>
        <nav>
            <NavLink href="" Match="NavLinkMatch.All">Start</NavLink>
            <NavLink href="results">Results</NavLink>
        </nav>
    </header>
    <main>
        @Body
    </main>
</div>

Layout/MainLayout.razor.css

Layout/MainLayout.razor.css
.shell {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}

header {
    position: sticky;
    top: 0;
    z-index: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px 16px;
    padding: 12px 16px;
    background: #2e1065;
    color: #fff;
}

.brand {
    color: #fff;
    font-weight: 700;
    text-decoration: none;
    margin-right: auto;
}

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

/* NavLink is a child component, so its <a> needs ::deep. */
nav ::deep a {
    color: #ddd6fe;
    text-decoration: none;
    padding: 6px 10px;
    border-radius: 8px;
}

nav ::deep a.active {
    background: #8b5cf6;
    color: #fff;
}

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

Pages/Question.razor

Pages/Question.razor
@page "/question/{Number:int}"
@implements IDisposable
@inject QuizState Quiz
@inject NavigationManager Navigation

<PageTitle>Question @Number</PageTitle>

@if (question is null)
{
    <h1>No question @Number</h1>
    <p>This quiz has @Quiz.Questions.Count questions.</p>
    <p><a href="">Back to the start</a></p>
}
else
{
    <div class="status">
        <span>Question @Number of @Quiz.Questions.Count</span>
        <span class="timer @(secondsLeft <= 5 && !answered ? "low" : "")" role="timer">@(answered ? "Done" : $"{secondsLeft} s")</span>
    </div>
    <div class="bar"><div style="width: @(BarPercent)%"></div></div>

    <h1>@question.Text</h1>

    <div class="choices">
        @for (var i = 0; i < question.Choices.Length; i++)
        {
            var index = i;
            <button class="choice @ChoiceClass(index)" disabled="@answered" @onclick="() => Choose(index)">@question.Choices[index]</button>
        }
    </div>

    @if (answered)
    {
        <p class="feedback" role="status">@Feedback</p>
        <button class="primary" @onclick="Next">@(Number < Quiz.Questions.Count ? "Next question" : "See results")</button>
    }
}

@code {
    [Parameter]
    public int Number { get; set; }

    private QuizQuestion? question;
    private int secondsLeft;
    private bool answered;
    private int? chosen;
    private Timer? timer;

    private int BarPercent => answered ? 0 : secondsLeft * 100 / QuizState.SecondsPerQuestion;

    // Created once. It stays stopped until OnParametersSet starts it.
    protected override void OnInitialized() =>
        timer = new Timer(OnTimer, null, Timeout.Infinite, Timeout.Infinite);

    // Runs for question/1 and again for question/2, because the Router keeps this component.
    protected override void OnParametersSet()
    {
        question = Quiz.Get(Number);
        answered = question is null || Quiz.IsAnswered(Number);
        chosen = Quiz.ChoiceFor(Number);
        secondsLeft = QuizState.SecondsPerQuestion;
        if (answered)
        {
            timer?.Change(Timeout.Infinite, Timeout.Infinite);
        }
        else
        {
            timer?.Change(1000, 1000);
        }
    }

    // Timer callbacks run outside Blazor's renderer. InvokeAsync moves the work onto it.
    private void OnTimer(object? state) => _ = InvokeAsync(() =>
    {
        if (answered) return;
        secondsLeft--;
        if (secondsLeft <= 0)
        {
            Finish(null);
        }
        StateHasChanged();
    });

    private void Choose(int index) => Finish(index);

    private void Finish(int? choice)
    {
        answered = true;
        chosen = choice;
        Quiz.Record(Number, choice);
        timer?.Change(Timeout.Infinite, Timeout.Infinite);
    }

    private void Next() =>
        Navigation.NavigateTo(Number < Quiz.Questions.Count ? $"question/{Number + 1}" : "results");

    private string ChoiceClass(int index)
    {
        if (!answered || question is null) return "";
        if (index == question.Answer) return "right";
        return index == chosen ? "wrong" : "";
    }

    private string Feedback => chosen switch
    {
        null => "Time is up. The right answer is marked in green.",
        var c when c == question!.Answer => "Correct.",
        _ => "Not quite. The right answer is marked in green."
    };

    // Called when you leave the question pages. A timer that is not disposed keeps firing.
    public void Dispose() => timer?.Dispose();
}

Pages/Results.razor

Pages/Results.razor
@page "/results"
@inject QuizState Quiz
@inject NavigationManager Navigation

<PageTitle>Results</PageTitle>

<h1>Results</h1>

<p class="score"><strong>@Quiz.Score</strong> of @Quiz.Questions.Count correct</p>
<p>@Message</p>

<ol class="review">
    @for (var i = 0; i < Quiz.Questions.Count; i++)
    {
        var number = i + 1;
        var question = Quiz.Questions[i];
        var choice = Quiz.ChoiceFor(number);
        <li>
            <span>@question.Text</span>
            @if (!Quiz.IsAnswered(number))
            {
                <span class="muted">Not answered yet.</span>
            }
            else if (choice is null)
            {
                <span class="wrong-text">Time ran out. Answer: @question.Choices[question.Answer]</span>
            }
            else if (choice == question.Answer)
            {
                <span class="right-text">Correct: @question.Choices[question.Answer]</span>
            }
            else
            {
                <span class="wrong-text">You chose @question.Choices[choice.Value]. Answer: @question.Choices[question.Answer]</span>
            }
        </li>
    }
</ol>

<button class="primary" @onclick="PlayAgain">Play again</button>

@code {
    private string Message => Quiz.AnsweredCount switch
    {
        0 => "You have not answered any questions yet.",
        var n when n < Quiz.Questions.Count => $"You answered {n} of {Quiz.Questions.Count} questions so far.",
        _ when Quiz.Score == Quiz.Questions.Count => "Every answer is correct.",
        _ => "Read the answers below, then try again."
    };

    private void PlayAgain()
    {
        Quiz.Reset();
        Navigation.NavigateTo("question/1");
    }
}

Pages/Start.razor

Pages/Start.razor
@page "/"
@inject QuizState Quiz
@inject NavigationManager Navigation

<PageTitle>Blazor Quiz</PageTitle>

<h1>Blazor Quiz</h1>

<p>@Quiz.Questions.Count questions about routing, services and the component lifecycle. You have @QuizState.SecondsPerQuestion seconds for each one.</p>

<div class="actions">
    <button class="primary" @onclick="Begin">Start the quiz</button>
    @if (Quiz.AnsweredCount > 0 && Quiz.AnsweredCount < Quiz.Questions.Count)
    {
        <a class="button" href="question/@(Quiz.AnsweredCount + 1)">Continue at question @(Quiz.AnsweredCount + 1)</a>
    }
</div>

<h2>How this app is built</h2>
<ul class="notes">
    <li>Each question is one route, <code>question/{Number:int}</code>. Going to the next question reuses the same component, so it resets in OnParametersSet.</li>
    <li>QuizState is a singleton service. Question pages write answers to it and the results page reads the score.</li>
    <li>The countdown uses a System.Threading.Timer. Its callback calls InvokeAsync, and the page disposes the timer when you leave.</li>
</ul>

@code {
    private void Begin()
    {
        Quiz.Reset();
        Navigation.NavigateTo("question/1");
    }
}

Services/QuizState.cs

Services/QuizState.cs
namespace BlazorQuiz.Services;

public sealed record QuizQuestion(string Text, string[] Choices, int Answer);

/// The questions and the player's answers. Registered as a singleton, so every page shares it.
public sealed class QuizState
{
    public const int SecondsPerQuestion = 15;

    // Question number (1-based) -> chosen choice, or null when time ran out.
    private readonly Dictionary<int, int?> answers = [];

    public IReadOnlyList<QuizQuestion> Questions { get; } =
    [
        new("Which directive makes a component a page with an address?",
            ["@page", "@layout", "@inject", "@code"], 0),
        new("Which route template matches /item/7 but not /item/seven?",
            ["/item/{id}", "/item/{id:int}", "/item/{id?}", "/item/{*id}"], 1),
        new("In Blazor WebAssembly, how long does a scoped service live?",
            ["One render", "One page visit", "Until the app closes", "One HTTP request"], 2),
        new("You go from /item/1 to /item/2 on the same page component. Which method runs again?",
            ["OnInitialized", "OnParametersSet", "Dispose", "The constructor"], 1),
        new("Why does a timer callback call InvokeAsync(StateHasChanged)?",
            ["It makes the timer faster", "It runs the update on Blazor's renderer", "It disposes the timer", "It reloads the page"], 1)
    ];

    public QuizQuestion? Get(int number) =>
        number >= 1 && number <= Questions.Count ? Questions[number - 1] : null;

    public bool IsAnswered(int number) => answers.ContainsKey(number);

    public int? ChoiceFor(int number) => answers.GetValueOrDefault(number);

    public void Record(int number, int? choice) => answers[number] = choice;

    public int AnsweredCount => answers.Count;

    public int Score => answers.Count(pair => pair.Value is int choice && Questions[pair.Key - 1].Answer == choice);

    public void Reset() => answers.Clear();
}

wwwroot/css/app.css

wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #8b5cf6;
    --line: #d9d3ea;
    --right: #16a34a;
    --wrong: #dc2626;
}

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

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

a {
    color: var(--accent);
}

h1 {
    font-size: 1.5rem;
    margin: 8px 0 16px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.1rem;
    margin: 28px 0 8px;
}

code {
    font-size: 0.9em;
}

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

button, a.button {
    display: inline-block;
    font: inherit;
    padding: 10px 16px;
    border-radius: 10px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
    text-decoration: none;
}

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

.actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.notes li {
    margin: 6px 0;
}

.muted {
    color: #777;
}

.status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #777;
}

.timer {
    font-weight: 700;
    font-variant-numeric: tabular-nums;
    color: var(--accent);
}

.timer.low {
    color: var(--wrong);
}

.bar {
    height: 6px;
    margin: 8px 0 4px;
    border-radius: 3px;
    background: var(--line);
    overflow: hidden;
}

.bar div {
    height: 100%;
    background: var(--accent);
    transition: width 0.9s linear;
}

.choices {
    display: grid;
    gap: 10px;
    margin-bottom: 16px;
}

.choice {
    text-align: left;
    padding: 14px 16px;
}

.choice:disabled {
    opacity: 1;
    color: inherit;
}

.choice.right {
    border: 2px solid var(--right);
    background: rgba(22, 163, 74, 0.12);
}

.choice.wrong {
    border: 2px solid var(--wrong);
    background: rgba(220, 38, 38, 0.1);
}

.feedback {
    font-weight: 600;
}

.score {
    font-size: 1.3rem;
    margin: 0;
}

.score strong {
    font-size: 2.4rem;
    color: var(--accent);
}

.review {
    padding-left: 22px;
}

.review li {
    margin: 10px 0;
}

.review span {
    display: block;
}

.right-text {
    color: var(--right);
}

.wrong-text {
    color: var(--wrong);
}

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

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>Blazor Quiz</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="BlazorQuiz.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>