I am working on a golf scorecard web app in Blazor (server side). I want it to do one of the following:
- On first render, it should load the scorecard (if any exist) from the local storage.
- On all following renders (changes) it should save the scorecard to the local storage, so that it is always updated with the newest values.
My code:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Console.WriteLine("Loading scorecard from local storage...");
var result = await ProtectedLocalStorage.GetAsync<Scorecard>("scorecard");
if (result.Success)
scorecard = result.Value;
StateHasChanged();
}
else
{
Console.WriteLine("Saving scorecard to local storage...");
if (scorecard != null)
await ProtectedLocalStorage.SetAsync("scorecard", scorecard);
}
}
I have checked that the Get
and Set
are reached as intended. I have also checked that on Set
, the values of the scorecard are as they should be. But once I reach Get
again, the score are reset to 0.
The Scores
are a list of HoleScore
's on the Scorecard
class, like this:
public class Scorecard
{
(...)
public List<HoleScore> Scores { get; } = new List<HoleScore>();
}
public record HoleScore
{
public Guid PlayerId { get; set; }
public int HoleNumber { get; set; }
public int NumberOfStrokes { get; set; };
}
It is the value NumberOfStrokes
that is reset to zero every time it loads (or maybe it's never saved). Why is that?
CodePudding user response:
The (de)seializer needs to be able to set properties.
//public List<HoleScore> Scores { get; } = new List<HoleScore>();
public List<HoleScore> Scores { get; set; } = new List<HoleScore>();