.netasp.net-coreblazorblazor-server-sidecheckboxlist

Blazor server : Previous checked box won't unticked automatically when clicking/ticking another checkbox


Let's just say I have data from my DB and I want to load it like this

in my razor component, I have this:

@if(selectedUser != null){
    @foreach (var items in User)
    {
        <tr>
            <td><input type="checkbox" @bind="valueChanged" @onclick="()=>ShowProfile(items)"> @items.CarestaffId </td>
            <td>@items.FirstName @items.MiddleInitial. @items.LastName</td>
            <td> @items.Title </td>
            <td> @items.Status  </td>
        </tr>
    }
}

Inside my c# code:

//this is a hidden div that will appear if checkbox was ticked
private bool DisplayProfile { get; set; } = true;

private bool valueChanged { get; set; } = false;

private User selectedUser;

private void ShowProfile(User user)
{
    valueChanged = true;
    selectedUser= user;
    if(valueChanged)
    {
        DisplayProfile = false;
    }
}

What I want is to automatically uncheck the previous checkbox when I check another checkbox because when I try to manipulate the checkbox, it's either all the checkboxes were checked / unchecked when the value changed.


Solution

  • the issue here is that you bind every check boxes to a single field valueChanged. So when this value is false, every check box will be "off", and vice-versa.

    What you might want to do is to bind the check boxes to a field in your User class. Something like:

    public class User {
       // your actuel class
       public bool IsChecked {get; set;} // add this field
    }
    ----
    <td><input type="checkbox" @bind="items.IsChecked" @onclick="()=>ShowProfile(items)"> @items.CarestaffId </td>
    
    

    By the way, I advise you to rename the name that you use in your for each loop:

    @foreach (var items in User) becomes @foreach (var user in Users), which will be more logical.