Venkat
Venkat

Reputation: 2186

maintain the values between tabs in blazor

Here is my code :

RiskForm.razor

 @page "/riskform"

RiskForm

 <MudTabs Elevation="4" Rounded="true" Centered="true" Color="@Color.Secondary">
<MudTabPanel Text="tab1">
    <Counter />
</MudTabPanel>
<MudTabPanel Text="tab2" />
<MudTabPanel Text="tab3" />
<MudTabPanel Text="tab4" />
<MudTabPanel Text="tab5" />
<MudTabPanel Text="tab6" />
<MudTabPanel Text="tab7" />

 </MudTabs>

Counter.razor is the default one.

 @page "/counter"

 <PageTitle>Counter</PageTitle>

 <h1>Counter</h1>


 <MudTextField @bind-Value="currentCount" Label="current count" Variant="Variant.Outlined" />
               

 <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

 @code {
 private int currentCount = 0;

  private void IncrementCount()
  {
    currentCount++;
  }
 }

When I increment the counter in tab1 and proceed to next tab and when I return to tab1 I lose the counter count. It initialises from 0 again.

How do i maintain the state of the counter incremented whilst browsing the tabs?

Upvotes: 0

Views: 860

Answers (1)

ggeorge
ggeorge

Reputation: 1630

To persist state you can do this:

public class PersistentState
{
    private int _currentCount;

    public int CurrentCounter
    {
        get { return _currentCount; }
        set
        {
            _currentCount = value;
            NotifyStateChanged();
        }
    }

    public event Action? OnChange;

    private void NotifyStateChanged() => OnChange?.Invoke();
}

And in Program.cs (.NET6) add service to container

builder.Services.AddScoped<PersistentState>();

Finally inject the PersistentState in Counter.razor

@page "/counter"
@inject PersistentState state

<h1>Counter</h1>

<p>Current count: @state.CurrentCounter</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    //private int currentCount = 0;

    private void IncrementCount()
    {
        //currentCount++;
        state.CurrentCounter++;
    }    
}

Upvotes: 1

Related Questions