Home > Net >  Trouble getting StateHasChanged to update an @if Statement
Trouble getting StateHasChanged to update an @if Statement

Time:10-15

So I'm having trouble getting my Razor page to update an if statement.

The idea is when a user selects a button, it'll recount the string looking for how many of X values there are, right now we are looking for spaces. If theres one space, I want the input field locked (the user has no reason edit it). If theres more than one space, its unlocked.

Below is the if statement holding the tags

                @if (NumOfSelectedValue <= 1)
            {
                <input class="form-control-sm" value="1" style="width: 40px" disabled />
            }
            else if (NumOfSelectedValue > 1)
            {
                <input class="form-control-sm" value="@NumOfSelectedValue" style="width: 40px" />
            }

And here is the logic on how I thought it would be updated.

    public void SpaceSelected() //ive used "async task"
{
    int NumOfSelectedValue = SelectedCell.Count(x => x == ' ');//counting how many spaces there are with Linq
    Console.WriteLine(NumOfSelectedValue);//post num of spaces in the console

    //other versions ive used 
    //StateHasChanged();//update the if statement
    //await InvokeAsync(StateHasChanged);

    InvokeAsync(StateHasChanged);
}

CodePudding user response:

Per your comments, you have a public property named NumOfSelectedValue. This is separate from the local variable NumOfSelectedValue you defined in SpaceSelected. Your solution is to not declare that local variable and instead just update the property:

public void SpaceSelected()
{
    NumOfSelectedValue = SelectedCell.Count(x => x == ' ');
    StateHasChanged();  // Probably not necessary unless you're calling this method in the background
}

Notice that we no longer have the int part in front of the assignment, which is what was declaring the variable.

  • Related