如何为bootstrap复选框创建EditorTemplate?

时间:2016-02-22 09:33:11

标签: asp.net asp.net-mvc twitter-bootstrap checkbox mvc-editor-templates

我正在使用引导程序模板,其复选框模板如下:

<div class="checkbox">
    <label>
        <input type="checkbox" class="checkbox style-1" checked="checked">
        <span>Checkbox 1</span>
    </label>
</div>

我需要一个MVC EditorTemplate来获取布尔值来使用这个模板。 MVC CheckBoxFor默认模板与此模板不同,它有另一个隐藏的输入字段来保存数据,并且没有显示复选框图标的跨度(它使用不能由css设置的默认图标)。

MVC CheckBoxFor默认模板:

<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">

我尝试了许多方法,但没有成功。例如,如果我使用如下所示的条件模板,则在提交后它不会返回值。

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>

有人可以帮忙吗?

更新

css代码的一部分相关于复选框图标:

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;
}

1 个答案:

答案 0 :(得分:5)

CheckBoxFor()方法生成2个输入以确保回发值(未选中复选框以不提交值以便隐藏输入确保提交false),并且您不应尝试更改此值行为。您对EditorTempate的尝试无法解决多种原因,包括复选框(具有2个状态)无法绑定到nullable bool(其中包含3个状态)且您的else块意味着即使选中了复选框,也始终会提交false的值。

相反,请使用CheckBoxFor()方法,但调整css选择器

<div class="checkbox">
    <label>
        @Html.CheckBoxFor(m => m.IsActive, new { @class = "checkbox style-1" })
        <span>Checkbox 1</span>
    </label>
</div>

将生成

<div class="checkbox">
    <label>
        <input type="checkbox" name="IsActive" class="checkbox style-1" ... value="true">
        <input type="hidden" name="IsActive" value="false">
        <span>Checkbox 1</span>
    </label>
</div>

所以你当前的选择器

label input[type=checkbox].checkbox + span:before {

span元素需要更改为

之后立即放置checkbox元素
label input[type=checkbox].checkbox ~ span:before {

与其他选择器同上(即将+更改为~)。 ~选择器匹配第二个元素(如果它前面是第一个元素),并且两者共享一个共同的父元素(参考General sibling selectors