What causes if/else expressions to be re-evaluated?

asp.net-core blazor c#

Question

Working off the Blazor hosted template, in my MainLayout.cshtml, I have something like:

@inject UserInfo userInfo
@if(userInfo.Name == "bob")
{
    <div class="login-panel">
        <p>Hi Bob!</p>
    </div>
}
else
{
    <LoginPanel />
}

and then in a separate Login.cshtml:

@inject UserInfo userInfo
async void Login()
{
    userInfo.Name = "bob";
}

But logging in doesn't cause a change to the 'login-panel' in MainLayout.cshtml. I was able to get this to work if everything is in a single file and I am only checking for whether a particular variable is null or not (see here), so I assume the Blazor framework has specific criteria which illicit a page to re-evaluate such blocks. Is this accurate? If so, what is the best way to force this re-evaluation?

Edit: I played around with it a bit more, eventually discovered the StateHasChanged protected member function, which I assume is called after Init has completed, hence why the previous example works. I think a working solution is to have my UserInfo object implement INotifyPropertyChanged, and then register a change handler inside MainLayout.cshtml to call StateHasChanged() for views that need to update when login status changes.

Accepted Answer

Yes. Blazor uses something called StateHasChanged just like INotifyPropertyChanged.

However the difference is, in XAML frameworks the XAML will only update those properties which has called INotifyPropertyChanged, but in Razor when StateHasChanged is called the UI framework will refresh the whole UI tree of the component (at least as of now) the element is residing. Then who has called the StateHasChanged if its not done by you. When an element gets an input (You are clicking a button) the blazor will automatically set the StateHasChanged under the hood.

More reads"

https://github.com/aspnet/Blazor/issues/409

https://learn-blazor.com/pages/data-binding/

https://github.com/aspnet/Blazor/issues/359

https://github.com/aspnet/Blazor/issues/407




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why