Cieja Cieja - 3 months ago 27
HTML Question

Pass boolean value by checkbox

I would like to pass my bool value by checkbox.

Here's my property

public bool MyBooleanValue{ get; set; } = true;


and here;s my HTML:

<input type="checkbox" id="@nameof(Model.MyBooleanValue)" name="my-boolean" value="1" class="" checked="checked" />

<label for="@nameof(Model.MyBooleanValue)">some text</label>

<input type="hidden" name="my-boolean" value="true" />


In default I would like to have checked field. What's wrong with this code ?
I use ASP.NET MVC 5.
I always get the same value

Answer

The simplest way is to use the MVC helper:

@Html.LabelFor(x => x.MyBooleanValue)
@Html.CheckBoxFor(x => x.MyBooleanValue)

You can check the FormCollection if the MyBooleanValue is true or false, depending on the checkbox state.


Alternatively use the simple html code:

<label for="MyBooleanValue">Some label text</label>
<input type="checkbox" id="MyBooleanValue" name="MyBooleanValue" checked="checked" value="Some value you want to pass if checked">

If the checkbox is checked the value will be passed in the form. Otherwise, the FormCollection does not contain this value.

Comments