Live Chat Icon For mobile
Live Chat Icon

How do you preserve the state in Blazor server-side?

Platform: Blazor| Category: General

Blazor Server is a stateful application framework that maintains a connection to the server. Its state will occur in the server memory known as circuit. We can preserve the state in Blazor server-side three ways:

  • Server-side storage
  • URL
  • Browser storage

The following example demonstrates how to preserve the state in Blazor server-side using browser storage.

Install the Blazored.SessionStorage NuGet package in the NuGet package manager to store the session data in Blazor. Add the Blazored SessionStorage configuration to the Blazor Server app.

[Startup.cs]

using Blazored.SessionStorage;
public class Startup
{
        public void ConfigureServices(IServiceCollection services)
    {
       //. . .
       services.AddBlazoredSessionStorage();
    }
}

[Index.razor]

@page "/"
@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

<button class="btn btn-primary" @onclick="Clear">Clear Session</button>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await sessionStorage.SetItemAsync("ID", "2021");
        await sessionStorage.SetItemAsync("Name", "John Smith");
    }
    public async void Clear()
    {
        // This will clear the session data.
        await sessionStorage.ClearAsync();
    }
}

Refer to this documentation for details.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.