I want to use bootstrap styled checkbox in my asp .net mvc form, however I find it very difficult. After hours looking for solution, I couldn't find anything that works for me.
Here is my HTML razor code, however checkbox doesn't show.
<div class="form-group">
@Html.LabelFor(c => c.IsSynchronize, new { @class = "col-sm-2 control-label" })
<div class="col-sm-10">
<div class="checkbox">
@Html.CheckBoxFor(model => model.IsSynchronize)
</div>
</div>
</div>
Here is rendered HTML :
<div class="checkbox">
<input data-val="true" data-val-required="Pole Synchronizacja jest wymagane." id="IsSynchronize" name="IsSynchronize" type="checkbox" value="true">
<input name="IsSynchronize" type="hidden" value="false">
</div>
How can I setup this simple thing in my form?
Razor offers two ways to generate checkboxes. The recommended approach is to use the input tag helper. Any boolean property of the PageModel will render a checkbox if it is passed to the asp-for attribute, so long as the property is not nullable: public class IndexModel : PageModel.
To create a custom checkbox, wrap a container element, like <div>, with a class of . custom-control and . custom-checkbox around the checkbox.
Just add value="true" to the input tag. And use a hidden with value="false" as shown below.
This solved the issue:
<div class="form-group">
<label class="col-sm-2"></label>
<div class="col-sm-10">
<div class="checkbox">
@Html.CheckBoxFor(model => model.Synchronize)
@Html.LabelFor(c => c.Synchronize)
</div>
</div>
</div>
its not working because of putting the class in div so add the class in checkbox
like this
<div class="form-group">
@Html.LabelFor(c => c.IsSynchronize, new { @class = "col-sm-2 control-label" })
<div class="col-sm-10">
@Html.CheckBoxFor(model => model.IsSynchronize ,new {@class="checkbox"})
</div>
</div>
btw i use icheck
which are a bit fancy you just have to add
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/bantikyan/icheck-bootstrap/master/icheck-bootstrap.min.css">
these libraries in header and in code use
<div class="form-group">
<div class="checkbox icheck-turquoise">
@Html.CheckBoxFor(model => model.IsSynchronize)
@Html.LabelFor(c => c.IsSynchronize, new { @class = "col-sm-2 control-label" })
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With