0

I have an issue with the Html.CheckboxFor() function on an MVC .NET 5 app.

The Razor code present is here

<div class="form-group">
    <div class="form-check">
        <label class="form-check-label">
            @Html.CheckBoxFor(i => i.IsDefault) Make Default
            <span class="form-check-sign"></span>
        </label>
    </div>
</div>

This generates the following HTML

<div class="form-group">
    <div class="form-check">
        <label class="form-check-label">
            <input data-val="true" data-val-required="The IsDefault field is required." id="IsDefault" name="IsDefault" type="checkbox" value="true" /> Make Default
            <span class="form-check-sign"></span>
        </label>
    </div>
</div>

Then, when I submit the form, if the box is checked, the posted FORM data from the browser dev tools POSTs

IsDefault: false
IsDefault: false

And if it is unchecked

IsDefault: false

I need to capture if the box is checked or not when the form is POSTed.

There is obviously something simple I am doing wrong, and I am sure I have checkboxes working in other parts of the app, and I have even tried copy-pasting, but I still cannot seem to get this working.

Rena
  • 30,832
  • 6
  • 37
  • 72
Matthew Warr
  • 86
  • 1
  • 10
  • 31
  • Hi @Matthew Warr, it should be work. Could you please share more details about your view and what is your backend code? – Rena Aug 23 '21 at 02:28

1 Answers1

0

You have to add the checked attribute to have the checkbox checked by default:

<input data-val="true" data-val-required="The IsDefault field is required." id="IsDefault" name="IsDefault" type="checkbox" value="true" checked /> Make Default

And to catch the checked/unchecked status in the action make sure you have a bool parameter in action named IsDefault which will catch the value of the check box.

Rahatur
  • 3,147
  • 3
  • 33
  • 49