简体   繁体   中英

Odd checkbox @onchange handling behaviour

In one of my (serverside) blazor pages I have the following construct:

  1. A table with one checkbox (amongst other things) in each row
  2. The checkbox has an onchange handler that will, in one constellation, remove an unchecked element from the "SelectableElements" collection:
@foreach (ViewModels.Element element in SelectableElements)
{
    <tr>
        <td>
            <input type="checkbox" checked="@IsChecked(element)" @onchange="(e) => OnCheckedChange(element, e)">
        </td>       
        <td>
            @element.Name
        </td>
    </tr>
}

// ...

protected void OnCheckedChange(Element element, ChangeEventArgs e)
{
    if (!(bool)e.Value)
    {
        SelectableElements.Remove(element);
    }    
}

When a checked element gets unchecked, it will disappear from the table. However, after the re-render the row beneath the removed row will have its checkbox unchecked, which is not what I want and I am not sure why that is happening? I can see in the debugger that IsChecked(...) returns true for the unchecked element.

The way I finally got this to work was like this:

<input type="checkbox" checked="@IsChecked(element)" @onclick:preventDefault @onclick="(e) => OnCheckedChange(element)">

This way I could handle the click myself without the checkmark being set by the default behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM