jorjj
jorjj

Reputation: 1599

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

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>

Upvotes: 53

Views: 110191

Answers (8)

Steve Shahbazi
Steve Shahbazi

Reputation: 175

You can try this:

<input type="checkbox" @bind-value="YourConditionTypeOfBool" checked="@(YourConditionTypeOfBool?"checked":null)"/>&nbsp; Is True
<span>My condition is @(YourConditionTypeOfBool?"True":"False")</span>

and in your code behind you need to define your YourConditionTypeOfBool variable, e.g.,:

@code{
     bool YourConditionTypeOfBool = true;
}

Upvotes: 7

Andrew Corrigan
Andrew Corrigan

Reputation: 1057

I was mainly led here because I just wanted to double-check the syntax because I was having a bit of brain-fade and this is still the top result on Google. My particular scenario is similar to Mike's in that I need the change event of the checkbox to drive whether another component is visible.

My solution uses Flores's suggestion to somewhat tidy up the idea that Mike had. This is just the bare bones of the dialog box that uses the mechanism in my case:

<div class="modal fade show" id="newsApprove" style="display:block;background-color:rgba(10,10,10,8);" aria-modal="true" role="dialog">
    <div class="modal-dialog" style="vertical-align:central">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Dates Active</h4>
                <button type="button" class="close" @onclick="@Cancel">&times;</button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <div class="input-group-text">
                        <input type="checkbox" aria-label="Active From Now?" id="activeNow" @bind-value="isChecked" />
                    </div>
                    <label class="form-check-label" for="activeNow">Render This Active Immediately?</label>
                </div>
                @if (!isChecked)
                {
                    <div>
                        <SfDateTimePicker TValue="DateTime" Min="DateTime.Now" @bind-Value="activeFrom"></SfDateTimePicker>
                    </div>
                }
                <SfDateTimePicker TValue="DateTime" Min="DateTime.Now" @bind-Value="activeTo"></SfDateTimePicker>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn-primary" @onclick="@Save">Approve</button>
                <button type="button" class="btn-secondary" @onclick="@Cancel">Cancel</button>
            </div>
        </div>
    </div>
</div>


@code {
    public DateTime activeTo { get; set; }
    public DateTime activeFrom { get; set; }

    private bool isChecked { get; set; } = true;

}

From there, if you do need to do some more processing when the checkbox change event is triggered; you can add a method that does the relevant processing and switches the value of isChecked accordingly.

Upvotes: 0

ricardo martinez
ricardo martinez

Reputation: 91

You can create a prop in your code behind to bind this value to and use the bind-value attr.

the prop definition would be something like public bool name {get;set;}

and then you can use the @bind-value attr

<input type="checkbox" id="name" @bind-value=name class="form-check-input">

or you can use the InputCheckbox built in component

<InputCheckbox @bind-Value="starship.IsValidatedDesign" />

https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#built-in-forms-components

*forgot mentioning the InputCheckbox has to be inside a EditForm

Upvotes: 4

user12228709
user12228709

Reputation:

Bind the checkbox value to a bool value.

in your @Code, bool checkedValue = false; // or true if it suits your use case

In your HTML:

<input type="checkbox" checked @bind="checkedValue">

The value of checkedValue will have the same value as your checkbox.

Upvotes: 44

Mike Wodarczyk
Mike Wodarczyk

Reputation: 1273

I don't think that any of the other answers do what I was looking for which was to:

  1. set the initial value of the checkbox to my variable that could be true or false
  2. let me respond to the checkbox onchange event to send the change back to the server or do some other work when checking/unchecking the checkbox.

My solution does both of these things, but requires the tag to be repeated for the checked and unchecked versions.

The razor file looks like this:

 @if (Approved)
 {
    <input type="checkbox" checked @onchange="@(async (e) => 
              await ToggleApprovedAsync(false))" />
 }
 else
 {
     <input type="checkbox"  @onchange="@(async (e) => 
              await ToggleApprovedAsync(true))" />
 }


@code {

    bool Approved;

    override async Task OnInitializedAsync()
    {
        Approved = await HttpClient.GetJsonAsync<bool>("../api/IsApproved");
    }

    async Task ToggleApprovedAsync(bool approved)
    {
        Console.WriteLine("Toggle Approved " + approved );
        if (approved)
        {
            await HttpClient.PostJsonAsync<bool>($"../api/Approve", null);
            Approved = true;
        }
        else
        {
            await HttpClient.PostJsonAsync<bool>($"../api/Disapprove", null);
            Approved = false;
        }
    }

}

Upvotes: 13

Manuel Alves
Manuel Alves

Reputation: 4013

@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;
    }

}

Upvotes: 40

enet
enet

Reputation: 45596

Remove the value attribute:

<input type="checkbox" id="addition" name="math" bind="@name" />

Add this property to the @function block or a class derived from BlazorCoponent:

public bool name {get;set;}

Now the value of your check box is bound to the name property and you can access this property, which contains the value of the check box, to retrieve the check box's value, just as you access other properties.

Hope this helps...

Upvotes: 10

Flores
Flores

Reputation: 8932

You have to remove the value="add" part.

and make sure name is a boolean.

Edit: complete example

@page "/test2"

<input type="checkbox" bind="@boolvalue" /><br/>
Boolvalue: @boolvalue<br/>
<button onclick="@toggle">toggle</button>

@functions
{

   public bool boolvalue { get; set; }

   void toggle()
   {
       boolvalue = !boolvalue;
   }
}

Upvotes: 5

Related Questions