I am working on learning Blazor form controls by building a simple todo application. Running into an issue where I am not sure how to handle a checkbox click since I cannot use both @bind and @onchange in the same form control. I can just use onchange and it works but it does not check the checkbox automatically when viewing items that have been marked complete.
Can someone please help me out and explain how I would handle the checkbox dynamically being checked or uncheck and also bind the boolean to it?
Thanks in advance, here is what I am doing currently which does not show checked in the completed view.
Todo Component
@using Project.Shared.Models
@inject HttpClient Http
<div><input type="checkbox" @onchange="CheckChanged" />@todo.Name</div>
@code {
[Parameter]
public Todo todo { get; set; }
private async Task CheckChanged()
{
todo.Complete = !todo.Complete;
await Http.PutAsJsonAsync("/api/Todo/Edit", todo);
}
}
Like I said this works, when I click the checkbox it will change the boolean in the database through the API, but the checkbox will not be checked when viewing completed items. When I do this it will check the checkbox on completed items but will not pick it up when it is clicked.
<div><input type="checkbox" @bind="todo.Complete" />@todo.Name</div>
I also tried using value which would be my approach with a text input type but it doesn't work on checkboxes.
I feel like using bind is the way to go but I cannot figure out how to pick up the checkbox selection when using bind.
You are painfully close.
<input type="checkbox" checked="@todo.Complete" @onclick="CheckChanged"/>@todo.Name</div>
Blazor will take checked="@someboolean"
and correctly render "checked" or nothing. I don't remember why I used @onclick, but this is from live and working code, so hopefully it works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With