Blazor two-way binding

Bence Mihucza 1 Reputation point
2021-06-18T06:34:36.067+00:00

I have a Blazor webassembly client. I want to bind a property to a checkbox type input field via a model class.

Model:

 public class Filter
 {
     public bool Selected { get; set; }
     public ItemType ItemType { get; }

     public Filter(ItemType itemType)
     {
         ItemType = itemType;
     }
    }
}

Binding:

@foreach (var armor in ArmorFilters)
{
    <div class="selector">
        <input type="checkbox" @bind-value="@armor.Selected"/>
        <span>@armor.ItemType.Name</span>
    </div>
}

ArmorFilters:

public IEnumerable<Filter> ArmorFilters { get; private set; } = Enumerable.Empty<Filter>();

My problem is the binding not working. When the checkbox is checked the setter of the Filter.Selected property will run, but when when I try to count the selected filters the result will be 0.

ArmorFilters.Count(af => af.Selected)

And when I update the Selected property from code it does not work as well.

foreach (var armor in ArmorFilters)
{
        armor.Selected = !armor.Selected;
}

Could you help me what am I doing wrong, please?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,404 questions
{count} votes