I am working with a bootstrap template and its checkbox template is like this:
<div class="checkbox">
<label>
<input type="checkbox" class="checkbox style-1" checked="checked">
<span>Checkbox 1</span>
</label>
</div>
I need an MVC EditorTemplate for boolean values to use this template. MVC CheckBoxFor default template is not like this template, it has another hidden input field to hold data and there is no span to show checkbox icon (it uses a default icon not stylable by css).
MVC CheckBoxFor default template :
<input checked="checked" data-val="true" data-val-required="required." id="IsActive"
name="IsActive" type="checkbox" value="true">
<input name="IsActive" type="hidden" value="false">
I tried many ways to do this with no success. For example if I use a conditional template like below, it does not return value after submit.
My Boolean EditorTemplate:
@model Boolean?
<div class="checkbox">
<label>
@if (Model.Value)
{
<input id="@ViewData.TemplateInfo.GetFullHtmlFieldId("")" name="@ViewData.TemplateInfo.GetFullHtmlFieldId("")"
type="checkbox" class="checkbox style-1" checked="checked" value="true" />
}
else
{
<input id="@ViewData.TemplateInfo.GetFullHtmlFieldId("")" name="@ViewData.TemplateInfo.GetFullHtmlFieldId("")"
type="checkbox" class="checkbox style-1" value="false" />
}
<span>@Html.LabelFor(m => m)</span>
</label>
</div>
Can anyone help please?
Update:
A part of css codes relevent to checkbox icon :
label input[type=checkbox].checkbox + span:before {
font-family: FontAwesome;
font-size: 12px;
border-radius: 0;
content: " ";
display: inline-block;
text-align: center;
vertical-align: middle;
padding: 1px;
height: 12px;
line-height: 12px;
min-width: 12px;
margin-right: 5px;
border: 1px solid #bfbfbf;
background-color: #f4f4f4;
font-weight: 400;
margin-top: -1px;
}
label input[type=checkbox].checkbox + span:before {
content: " ";
}
label input[type=checkbox].checkbox:checked + span:before {
content: "";
color: #2e7bcc;
}
label input[type=checkbox].checkbox:checked + span {
font-weight: 700;
}
class="checkbox style-1"
using theCheckBoxFor()
method. But its clear your not understanding theCheckBoxFor()
method. Firstly it generates the hidden input so a value is always posted back (unchecked checkboxes do not submit a value). Second you cannot bind a checkbox to anullable bool
- a checkbox has 2 states butbool?
has 3 states and yourEditorTemplate
makes no sense - yourelse
block generates a checkbox which will always submit a value offalse
no matter what if its checked or not. – Sybaris<div class="checkbox"> <label> @Html.CheckBoxFor(m => m.EmaiToCustomer, new { @class = "checkbox style-1" }) <span> @Html.LabelFor(m => m.EmaiToCustomer)</span> </label> </div>
If yes, when the hidden input comes after checkbox input it causes checkbox icon not visible anymore! – Adenoidcss
selectors which best guess is currently something like.checkbox + label
) – Sybaris