Aaron Hudon
Aaron Hudon

Reputation: 5839

Blazor - Binding to a collection of objects

Blazor preview v9

What is required to bind an EditForm to a collection of objects? When I setup my EditForm to a collection of objects, exposing and binding their bool property, when you click the checkbox they are immediately un-checked.

@page "/sompage"

<EditForm Model="MyModel">
    @foreach(var item in MyModel.Items)
    {
        <label>
        <InputCheckbox @bind-Value="item.BoolProperty" />
        @item.Text</label>
    }
</EditForm>

@code
{
    public class SomeModel
    {
        public IEnumerable<SomeItem> Items { get;set; } = new List<SomeItem>();
    }
    public class SomeItem
    {
        public string Text { get;set; }
        public bool BoolProperty { get;set; }
    }
}

Upvotes: 3

Views: 5208

Answers (1)

Aaron Hudon
Aaron Hudon

Reputation: 5839

The solution, much like ASP.NET binding, is to expose mutable collections. As I had originally exposed the Items as IEnumerable<SomeItem> the binding magic of Blazor can not update the target collection.

Changing Items List<SomeItem> does this trick.

Upvotes: 8

Related Questions