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?
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>
Under mvc a true/false checkbox based on the model value (boolean) also has a hidden field with the same name (supposedly to cater for when you don't check the box you still get a value in the Forms collection)
Its this hidden field that stops the checkbox working in bootstrap format.
A bootstrap styled checkbox from what I can see will never display properly under mvc using @Html.CheckBoxFor
This is what i did to get it working
<div class="checkbox">
<input type="checkbox" value="@Model.propertyname" id="[same as property name]" name="[same as property name]" />
<label for="propertyname">any label you like</label>
</div>
Unfortunately the model isn't updated when you post the form and you have to handle that in the HttpPost'ed action
Doesn't seem to work for me, the checkbox changes shape (the corners round) but acts as though its read only, still working on it.
Just a note to your solution, you could use the offset to keep the controls aligned which don't have labels, so remove
<label class="col-sm-2"></label>
And add col-md-offset-2 instead:
<div class="col-md-10 col-sm-offset-2">