Blazor default template application issue

Haviv Elbsz 2,151 Reputation points
2023-09-28T14:59:18.6+00:00

Hi all. in the default template application of blazor when clicking the button the count variable is increasing by 1. but when navigate to other component and then return to the Counter component the count value is reset to 0 what changes I need to do in this default template application to fix this so when returning the value stays is was left. Thank you very much.

Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-09-29T03:50:13.2633333+00:00

    Hi @Haviv Elbsz

    You can use In-memory state container service or Browser Storage leverages (ASP.NET Core Data Protection for localStorage and sessionStorage) to preserve the data.

    For example, using In-memory state container service:

    1.Create a StateContainer class in the Models folder (This sample is a Blazor WebAssembly App):

        public class StateContainer
        {
            private int? savedCounter;
    
            public int Counter
            {
                get => savedCounter ?? 0;
                set
                {
                    savedCounter = value;
                    NotifyStateChanged();
                }
            }
    
            public event Action? OnChange;
    
            private void NotifyStateChanged() => OnChange?.Invoke();
        }
    

    2.Register the StateContainer class in the program.cs file:

    builder.Services.AddSingleton<StateContainer>();
    

    3.In the Counter component, use the following code:

    @page "/counter"
    @using BlazorWebAssemblyApp2.Models;
    @implements IDisposable
    @inject StateContainer StateContainer
    <PageTitle>Counter</PageTitle>
    
    <h1>Counter</h1>
    
    <p role="status">Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
        protected override void OnInitialized()
        {
            StateContainer.OnChange += StateHasChanged;
    
            currentCount = StateContainer.Counter;
        }
        private void IncrementCount()
        {
            currentCount++;
            StateContainer.Counter = currentCount;
        }
        public void Dispose()
        {
            StateContainer.OnChange -= StateHasChanged;
        }
    }
    
    

    The result as below:

    image1

    If your application is an Blazor server application, you can also use the above code, or refer to the following code to use ProtectedBrowserStorage to preserve the data, it will also get the same result.

    @page "/counter"
    
    @using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
    @inject ProtectedSessionStorage ProtectedSessionStore
    <h1>Counter</h1>
    
    <p>Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
    
        protected override async Task OnInitializedAsync()
        {
            var result = await ProtectedSessionStore.GetAsync<int>("count");
            currentCount = result.Success ? result.Value : 0;
        }
    
        private async void IncrementCount()
        {
            currentCount++;
            await ProtectedSessionStore.SetAsync("count", currentCount);
        }
    }
    

    More detail information, see ASP.NET Core Blazor state management.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 81,981 Reputation points Volunteer Moderator
    2023-09-28T15:39:33.6066667+00:00
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.