user2017341
user2017341

Reputation: 175

How can I bind checkbox value and invoke a method on change?

I fill my to do list by invoking api, so some checkboxes can be checked:

enter image description here

I would like to invoke a method if someone click on my checkbox. How can I use bind and onchange together?

@foreach (var todo in todos)
{
    <li style="margin: 20px;">
        <input type="hidden" @bind="todo.Id" />
        <input type="checkbox" @bind="todo.IsComplete" @onchange="eventArgs => { CheckboxClicked(todo, eventArgs.Value); }" />
        <input @bind="todo.Name" />
    </li>
}

Upvotes: 1

Views: 333

Answers (1)

enet
enet

Reputation: 45596

@foreach (var todo in todos)
{
    <li style="margin: 20px;">
        <input type="hidden" @bind="todo.ID" />
       @* <input type="checkbox" checked="@todo.IsComplete" @onchange="eventArgs => 
         { CheckboxClicked(todo, eventArgs.Value); }" /> *@

         <input type="checkbox" checked="@todo.IsComplete" @onchange="@((args) => 
         { todo.IsComplete = (bool) args.Value; } )" />

        <input @bind="todo.Name" />
    </li>
}

@code{

   private List<ToDo> todos = new List<ToDo>{new Todo{ID = 1, IsComplete = false, Caption = "I have a bike", Name = "Name1"},
new Todo{ID = 1, IsComplete = false, Caption = "I have a car", Name = "Name2"},
new Todo{ID = 1, IsComplete = false, Caption = "I have a boat", Name = "Name3"}};

 //   private async Task CheckboxClicked(ToDo todo, ChangeEventArgs e)
  //  {

  //  }
    

    public class ToDo
    {
        public int ID { get; set; }
        public bool IsComplete{ get; set; }
        public string Caption { get; set; }
        public string Name { get; set; }
       
    }

}

Upvotes: 2

Related Questions