Search code examples
asp.netblazorblazor-editform

Why is the binding of my Blazor InputCheckbox component not working as expected?


I'm using an EditForm bound to a model to filter some data in my Blazor application. As part of this, I have a InputCheckbox for each item in a list, which is bound to a bool attribute of that individual item. When I populate the list of objects of this class, I'm setting the initial value of the Selected to be true, so that every item is checked by default.

When the EditForm is submitted, however, the value of the attribute for the given item remains true, even if I have unchecked the box.

This is my EditForm:

<EditForm Model="FilterCriteria" OnSubmit="PerformFiltering" FormName="Filtering">
    <label>Test Properties</label>
    @foreach (var property in Properties)
    {
        <label>
            <InputCheckbox name="property" @bind-Value="FilterCriteria.SelectedProperties.Where(p => p.PropertyId == property.Id).FirstOrDefault().Selected" />
            @property.Name
        </label>
    }
    <button type="submit">Search</button>
</EditForm>

This is the partial class for my razor component:

public partial class Home
{
    private List<Property> Properties { get; set; }

    [SupplyParameterFromForm]
    private FilteringCriteriaModel? FilterCriteria { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Properties = new List<Property>();

        for (var i = 0; i < 10; i++)
        {
            Properties.Add(new Property
            {
                Id = Guid.NewGuid(),
                Name = i.ToString()
            });
        }

        FilterCriteria = new FilteringCriteriaModel();


        foreach (var property in Properties)
        {
            FilterCriteria.SelectedProperties.Add(new PropertySelection
            {
                PropertyId = property.Id,
                Selected = true
            });
        }
    }

    private void PerformFiltering()
    {
        foreach (var property in FilterCriteria.SelectedProperties)
        {
            Console.WriteLine($"{property.PropertyId}: {property.Selected}");
        }
        return;
    }
}

This is the Property class:

public class Property
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

This is the PropertySelection class:

public class PropertySelection
{
    public Guid PropertyId { get; set; }
    public bool Selected { get; set; }
}

This is the FilteringCriteriaModel class:

public class FilteringCriteriaModel
{
    public List<PropertySelection> SelectedProperties = new List<PropertySelection>();
}

I'm using ASP.NET Core Blazor, on .NET 8.

Any and all help is much appreciated :)


Solution

  • In my case, I needed to set the rendermode to InteractiveServer, and it started picking up the changes.