.NET Core Blazor: How to get the Checkbox value if it is checked?

jorjj picture jorjj · Jul 8, 2018 · Viewed 25.1k times · Source

I am trying to find to get the checkbox value if it is checked using Blazor framework, but I couldn't find any method for it so far. When I put the binding in the checkbox, it is always checked. I couldn't figured it out how to get the checked value.

This is my code:

<input type="checkbox" id="addition" name="math" value="add" bind="@name" />
<label for="addition">Addition</label>

Answer

Manuel Alves picture Manuel Alves · Nov 27, 2018
@page "/registration"

    @foreach (var club in ClubList())
    {
        <input type="checkbox" @onchange="eventArgs => { CheckboxClicked(club, eventArgs.Value); }" />@club<br />
    }

@functions {

    public List<string> ClubMember { get; set; } = new List<string>();
    void CheckboxClicked(string clubID, object checkedValue)
    {
        if ((bool)checkedValue)
        {
            if (!ClubMember.Contains(clubID))
            {
                ClubMember.Add(clubID);
            }
        }
        else
        {
            if (ClubMember.Contains(clubID))
            {
                ClubMember.Remove(clubID);
            }
        }
    }

    public List<String> ClubList()
    {
        // fetch from API or...
        List<String> c = new List<String>();
        c.Add("Clube01");
        c.Add("Clube02");
        return c;
    }

}