Search code examples
blazorblazor-webassembly

Update variable in the layout from component - Blazor


I have layout defined as such

@layout MainLayout

@inherits LayoutComponentBase

<CascadingValue Value="this">
    @Body

    @("_total " + _total)

    @("_perPage " + _perPage)

</CascadingValue>

@code {
    public int _total;
    public int _perPage;
}

Then in component receive the layout reference

[CascadingParameter] public Layout Layout { get; set; }

And the set it as such in

protected override async Task OnInitializedAsync()
    {
    Layout._total = 3;
    Layout._perPage = 3;
}

Problem is the values in the Layout don't get updated. I tried with 'StateHasChanged` after the setter statements but that doesn't seem to make a difference


Solution

  • You are setting the value, but there's nothing driving a StateHasChanged event in the Layout component. You can:

    1. Add a method to the Layout to explicitly call StateHasChanged which you call from your component.
    2. Make your values properties and add setters that call StateHasChanged - can get messy!.
    3. Add a specific method to set the values and call StateHasChanged as detailed in Surinder's answer.