Question What am I doing wrong with StateHasChanged

JohnF

New member
Joined
Jan 10, 2025
Messages
1
Programming Experience
10+
Folks:

I am gearing up for a project now in Proof of Concept stage. My specific issue is I have a component. It is simply a box. It is three deep from page so Page -> Major Component -> The Status Box in question. This is going to be a monitoring app. So - little to no user interaction. Changes come from the outside. (Like a fantasy football scoreboard.) UI change needs to occur based on events outside the application - identified by non-UI server side code.

My current task is simply to get the component to work. So I have put a button on the page component - and I kick the code from there. What I want to change is simply the css style background-color. The color is contained in a bind variable. After I change the color - I call StatusHasChanged(). The code seems to be working. I can breakpoint on the property get and observe is is executed after the button is pushed. Further - I can breakpoint on the StatusHasChanged and observe the color has indeed changed - as I expected. But the color never makes it to the UI. The background color of the box on the web client never changes.

Note - this is razor - not blazor. What I want to accomplish is very simple. I simply want the color of the box to change.

My .razor is:
HTML:
@inherits ForkStatusBoxBase


<style>
    .box {
        width: 25px;
        height: 25px;
        vertical-align: middle;
        background-color: @BackgroundColor;
        border: 2px solid black;
        padding: 5px;
        margin: 5px;
    }
</style>



<div class="box" @bind="BackgroundColor" />



My .razor.cs code behind is
C#:
public class ForkStatusBoxBase : ComponentBase
{
    string backgroundColor = "lightblue";




    public string BackgroundColor
    {
        get { return backgroundColor; }
        set { backgroundColor = value; }
    }

    public void GrantedFork()
    {

        backgroundColor = "green";
        StateHasChanged();

    }

}
Any help would be appreciated.
 
Last edited by a moderator:
I guess I'm learning something new. I didn't know that changing a backend value in Razor would cause the web client to re-download and re-render the web page. I always thought that was a Blazor thing rather than a Razor thing.

Have you watched the network traffic to see if the web browser gets an update from the server? Does the updated HTML have the new values?
 
Back
Top Bottom