Can the state of the Counter in the example Blazor project be preserved between page switches?

前端 未结 4 935
情书的邮戳
情书的邮戳 2021-01-15 21:37

In the default example project for both server-side Blazor and WebAssembly Blazor projects, the Counter example resets to 0 every time you move between the pages. However, o

4条回答
  •  梦毁少年i
    2021-01-15 22:09

    For server side Blazor if you want the counter value to be persisted/updated on all tabs/clients you could simply store it in a static variable and rerender if the value changes.

    @page "/counter"
    
    

    Static Counter

    Current static count: @currentCount

    @code { public static int currentCount = 0; private void IncrementCount() { currentCount++; StaticCount.FireUpdate(); } protected override void OnInitialized() { base.OnInitialized(); StaticCount.NewCounterValue += OnNewCounterValue; } void OnNewCounterValue(object sender, EventArgs e) { InvokeAsync(() => { StateHasChanged(); }); } public void Dispose() { StaticCount.NewCounterValue -= OnNewCounterValue; } } @code{ public static class StaticCount { public static event EventHandler NewCounterValue; public static void FireUpdate() { NewCounterValue?.Invoke(null, new EventArgs()); } } }

    You could also do this with a (singleton) service and even persist the value in a database if you want to keep the value between server restarts.

提交回复
热议问题