MVC 4: Ví dụ này cho thấy chi tiết việc triển khai các mẫu boolean cho danh sách thả xuống có chứa giá trị Có, Không và Không được đặt và cũng xử lý các giá trị bool null. Lấy cảm hứng từ Darin Dimitrov và Jorge - Cảm ơn bạn.
Mẫu 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)
}
Xem:
<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>
Nguồn
2013-03-23 20:53:52