I´m trying to save some objects of classes which I have created to the session storage of my Blazor Wasm application to save the state after a refresh (F5). I followed the tutorial of Bradley Wells (https://wellsb.com/csharp/aspnet/blazor-write-to-localstorage/) assuming that everything works similar if I use session storage instead of local storage.
If I tried my code using a basic datatype like string, it worked like a charm, the value "testmessage" was still displayed after a refresh of the page.
protected override async Task OnInitializedAsync()
{
testString = await sessionStorage.GetItemAsync<string>("sample");
}
// Method gets triggered on button press
async Task TestMethodCanBeDeleted()
{
testString = "testmessage";
await sessionStorage.SetItemAsync<string>("sample", testString);
}
As soon as I try to save e.g. an instance of the class MyCustomObject instead of string, it doesn´t work anymore. Do I have to create an instance of the class in the session storage at first? If yes, how.
If someone knows another (maybe even better) way how to save "non-basic" datatypes in the session storage, please comment.
Edit: Bradley Wells answered a comment on his page writing that it is possible to save objects to the session storage using Blazored, but didn´t explain how.
You will need to convert your object to json or any other string format so that it can be saved in session. And when you retrieve it back, you can convert that json to your object.
To convert to json you can use Newtonsoft Json.NET
using Newtonsoft.Json;
Convert object to string:
string json = JsonConvert.SerializeObject(myCustomObject);
await sessionStorage.SetItemAsync<string>("sample", json);
Convert string to object:
json = await sessionStorage.GetItemAsync<string>("sample");
MyCustomObject myCustomObject = JsonConvert.DeserializeObject<MyCustomObject>(json);
You can also use the new .net core System.Text.Json
using System.Text.Json;
using System.Text.Json.Serialization;
Convert object to string:
string json = JsonSerializer.ToString<MyCustomObject>(myCustomObject);
await sessionStorage.SetItemAsync<string>("sample", json);
Convert string to object:
json = await sessionStorage.GetItemAsync<string>("sample");
MyCustomObject myCustomObject = JsonSerializer.Parse<MyCustomObject>(json);