Search code examples
c#data-bindingblazorblazor-server-sidemudblazor

Blazor binding checkbox in foreach loop


I would like to bind at runtime a checkbox in a foreach loop.

I get this error :

Cannot assign to 'item' because it is a 'foreach iteration variable'


@foreach (var item in myPerson.Persons) {
    <MudCheckBox @bind-Checked=item.IsAlive />
}

@code{
    var myPerson = new MyPerson();
    
    public class MyPerson
    {
        public List<Person> Persons { get; set; }
    }   

    public class Person
    {
        public bool IsAlive { get; set; }
    }
}

Thanks,


Solution

  • The binding appears to be correct, are you sure you're properly initializing the myPerson object?

    Below is an example of code that works flawlessly:

    <ul>
        @foreach (var person in _myPerson.Persons)
        {
            <li>@person</li>
        }
    </ul>
        
    @foreach (var item in _myPerson.Persons)
    {
        <MudCheckBox @bind-Checked="@item.IsAlive" Label="@item.Name" />
    }
    
    @code {
    
        private readonly MyPerson _myPerson = new MyPerson()
        {
            Persons = new List<Person>()
            {
                new Person("Bob"),
                new Person("Alice")
            }
        };
    
        public class MyPerson
        {
            public List<Person> Persons { get; set; }
        }
    
        public class Person
        {
            public Person(string name)
            {
                Name = name;
            }
    
            public string Name { get; }
            public bool IsAlive { get; set; }
    
            public override string ToString() => IsAlive ? $"{Name} is alive" : $"{Name} is dead";
        }
    }