Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6081

ProtectedLocalStorage.SetAsync() doesn't save nested properties?

I am working on a golf scorecard web app in Blazor (server side). I want it to do one of the following:

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?

Upvotes: 1

Views: 749

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

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

or, as has come up in the comments:

  public List<HoleScore> Scores { get; init; } = new List<HoleScore>();

to provide unintended access.

Upvotes: 1

Related Questions