Darren
Darren

Reputation: 23

Persistent Value in Blazor Server Side Application

I need to have a value available to all pages in my Blazor server side application (An AccountID). Obviously any page variable or global variable is reset/lost on page refresh.

I looked at all the various options in terms of cookies, local storage and session storage and it looks like the best fit would be the use of cookies with Javascript Interop.

Is this the best way and what is the best way to implement this?

Upvotes: 1

Views: 1611

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170257

I'd not mess with JS-interop if there is no real need to (which there isn't in your case). There are many 3rd party packages that can help. Blazored.LocalStorage for example.

  1. Add the package to your .csproj:
<PackageReference Include="Blazored.LocalStorage" Version="4.2.0" />
  1. for server sice Blazor, add it during ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
  services.AddBlazoredLocalStorage();
}
  1. and use it in your Razor pages:
@inject Blazored.LocalStorage.ILocalStorageService localStorage

@code {

  protected override async Task OnAfterRenderAsync(bool firstRender)
  {
    await localStorage.SetItemAsync("name", "Darren");

    var name = await localStorage.GetItemAsync<string>("name");
  }
}

And if you're using dotnet 5 or up, have a look at this: https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-6.0&pivots=server#save-and-load-data-within-a-component

Upvotes: 1

Related Questions