In the default example project for both server-side Blazor and WebAssembly Blazor projects, the Counter example resets to 0 every time you move between the pages. However, o
It looks like this exact scenario is discussed in https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser
Seems Blazor just doesn't handle it out-of-the-box, but you just need to use localStorage
or sessionStorage
.
Using the Blazor.Extensions.Storage
NuGet package (https://github.com/BlazorExtensions/Storage):
@page "/counter"
@inject ISessionStorage SessionStorage
@using Blazor.Extensions.Storage.Interfaces
Counter
Current count: @currentCount
@code {
private int currentCount = 0;
protected override async Task OnInitializedAsync()
{
currentCount = await SessionStorage.GetItem("counter");
}
private async void IncrementCount()
{
currentCount++;
await SessionStorage.SetItem("counter", currentCount);
}
}