Hi @Haviv Elbsz
You can use In-memory state container service or Browser Storage leverages (ASP.NET Core Data Protection for localStorage
and sessionStorage
) to preserve the data.
For example, using In-memory state container service:
1.Create a StateContainer class in the Models folder (This sample is a Blazor WebAssembly App):
public class StateContainer
{
private int? savedCounter;
public int Counter
{
get => savedCounter ?? 0;
set
{
savedCounter = value;
NotifyStateChanged();
}
}
public event Action? OnChange;
private void NotifyStateChanged() => OnChange?.Invoke();
}
2.Register the StateContainer class in the program.cs file:
builder.Services.AddSingleton<StateContainer>();
3.In the Counter component, use the following code:
@page "/counter"
@using BlazorWebAssemblyApp2.Models;
@implements IDisposable
@inject StateContainer StateContainer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
protected override void OnInitialized()
{
StateContainer.OnChange += StateHasChanged;
currentCount = StateContainer.Counter;
}
private void IncrementCount()
{
currentCount++;
StateContainer.Counter = currentCount;
}
public void Dispose()
{
StateContainer.OnChange -= StateHasChanged;
}
}
The result as below:
If your application is an Blazor server application, you can also use the above code, or refer to the following code to use ProtectedBrowserStorage to preserve the data, it will also get the same result.
@page "/counter"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
protected override async Task OnInitializedAsync()
{
var result = await ProtectedSessionStore.GetAsync<int>("count");
currentCount = result.Success ? result.Value : 0;
}
private async void IncrementCount()
{
currentCount++;
await ProtectedSessionStore.SetAsync("count", currentCount);
}
}
More detail information, see ASP.NET Core Blazor state management.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion