我为布尔类型创建了一个编辑器模板,我的问题是当模型属性不可为空时,复选框的默认行为会被修改,例如,如果模型值为true
然后显示视图中的复选框而不选中。我究竟做错了什么???这是代码。
@model Nullable<bool>
@{
var listItems = new[]
{
new SelectListItem { Value = "null", Text = "Sin Valor" },
new SelectListItem { Value = "true", Text = "Si" },
new SelectListItem { Value = "false", Text = "No" }
};
}
@if (ViewData.ModelMetadata.IsNullableValueType)
{
@Html.DropDownListFor(model => model.Value, listItems)
}
else
{
@Html.CheckBox("", ViewData.TemplateInfo.FormattedModelValue)
}
答案 0 :(得分:1)
不确定您在复选框中使用的ViewData.ModelMetadata.v
是什么意思。你试过了吗?
@model Nullable<bool>
@{
var listItems = new[]
{
new SelectListItem { Value = "null", Text = "Sin Valor" },
new SelectListItem { Value = "true", Text = "Si" },
new SelectListItem { Value = "false", Text = "No" }
};
}
@if (ViewData.ModelMetadata.IsNullableValueType)
{
@Html.DropDownList("", new SelectList(listItems, "Value", "Text", Model))
}
else
{
@Html.CheckBox("", Model.Value)
}
答案 1 :(得分:0)
此示例详细显示了包含Yes,No和Not Set值的下拉列表的布尔模板的实现,并且还处理了null bool值。受到Darin Dimitrov和Jorge的启发 - 谢谢。
模型 Student.cs
[Display(Name = "Present:")]
[UIHint("YesNo")]
public bool? IsPresent { get; set; }
DisplayTemplates: YesNo.cshtml
@model Nullable<bool>
@if (Model.HasValue)
{
if (Model.Value)
{ <text>Yes</text> }
else
{ <text>No</text> }
}
else
{ <text>Not Set</text> }
EditorTemplates: YesNo.cshtml
@model Nullable<bool>
@{
var listItems = new[]
{
new SelectListItem { Value = "null", Text = "Not Set" },
new SelectListItem { Value = "true", Text = "Yes" },
new SelectListItem { Value = "false", Text = "No" }
};
}
@if (ViewData.ModelMetadata.IsNullableValueType)
{
@Html.DropDownList("", new SelectList(listItems, "Value", "Text", Model))
}
else
{
@Html.CheckBox("", Model.Value)
}
查看:
<div class="editor-label">
@Html.LabelFor(model => model.IsPresent )
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IsPresent )
@Html.ValidationMessageFor(model => model.IsPresent )
</div>