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
For server side Blazor if you want the counter value to be persisted/updated on all tabs/clients you could simply store it in a static variable and rerender if the value changes.
@page "/counter"
Static Counter
Current static count: @currentCount
@code {
public static int currentCount = 0;
private void IncrementCount()
{
currentCount++;
StaticCount.FireUpdate();
}
protected override void OnInitialized()
{
base.OnInitialized();
StaticCount.NewCounterValue += OnNewCounterValue;
}
void OnNewCounterValue(object sender, EventArgs e)
{
InvokeAsync(() =>
{
StateHasChanged();
});
}
public void Dispose()
{
StaticCount.NewCounterValue -= OnNewCounterValue;
}
}
@code{
public static class StaticCount
{
public static event EventHandler NewCounterValue;
public static void FireUpdate()
{
NewCounterValue?.Invoke(null, new EventArgs());
}
}
}
You could also do this with a (singleton) service and even persist the value in a database if you want to keep the value between server restarts.