Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I save string to session storage in Blazor Server in the _Host.cshtml file

Like the title says, I am wondering how to save strings to session storage in Blazor Server in the _Host.cshtml file to then read them in the other Blazor pages. I am getting data from a LiteDB database. I tries using the Blazored.SessionStorage package, but I got an error, without a direct code?, it just redirected me. This happens when I try to do the right way of putting the await before the line.

SessionStorage.SetItemAsync("Title", (homepageObj != null) ? "Working" : "Working");

This is the code I try to do so it doen’t give me an error. But the problem is, when I try to then read the data just below the saving, it returns as empty. Code for reading the session:

var val = SessionStorage.GetItemAsStringAsync("Title");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Session object to store and retrive data from session storage.Try the following code to save the string in the session storage from the _Host.cshtml page.

Example:

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
    
    @{
        HttpContextAccessor.HttpContext.Session.SetString("Title", (homepageObj != null) ? "Working" : "Not Working");
    }

To read the data from other blazor pages use the same HttpContextAccessor to access the session data.

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

@code {
    private string title;

    protected override void OnInitialized()
    {
        title = HttpContextAccessor.HttpContext.Session.GetString("Title");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading