ASP.NET Core Blazor State Management

Last Updated on July 1, 2022 by Pupli

We can use ASP.NET Core Protected Browser Storage:

Use the Local Storage

@page "/"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage BrowserStorage

<h1>Local Storage!</h1>

<input class="form-control" @bind="currentInputValue" />
<button class="btn btn-secondary" @onclick="Save">Save</button>
<button class="btn btn-secondary" @onclick="Read">Read</button>
<button class="btn btn-secondary" @onclick="Delete">Delete</button>

@code {
  string currentInputValue;

  public async Task Save()
    await BrowserStorage.SetAsync("name", currentInputValue);

  public async Task Read()
    var result = await BrowserStorage.GetAsync<string>("name");
    currentInputValue = result.Success ? result.Value : "";

  public async Task Delete()
    await BrowserStorage.DeleteAsync("name");

Use the Session Storage

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedSessionStorage ProtectedSessionStore