Our latest


Announcements, Blogs, Releases and much much more...

  • Read our latest news and announcements, hot off the press.

Announcements






Category Blazor FAQ

Published on 12-May-2021

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

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:

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();
    }
}


Microsoft Refer to this documentation for details.

Created on 12-May-2021 Last updated 23-May-2021

Assigned Tag
  • Blazor
  • FAQ