渲染可空布尔的复选框 [英] Rendering Nullable Bool as CheckBox
问题描述
我是新从WebForms的MVC的。我视图模型字段类型布尔?
,默认情况下, EditorFor()
渲染此字段作为一个DropDownList以未设置选项。我想preFER以使其为复选框,如果该值为null,只需将其设置为未选中状态。
I'm new from WebForms to MVC. I have view model field with the type bool?
and, by default, EditorFor()
renders this field as a DropDownList with a "Not Set" option. I would prefer to render it as a CheckBox and, if the value is null, just set it to unchecked.
字段名称为 RFP.DatesFlexible
,所以我在我看来,写了下面的标记:
The field name is RFP.DatesFlexible
and so I wrote the following markup in my view:
<input type="checkbox" id="RFP_DatesFlexible" name="RFP.DatesFlexible" />
<label for="RFP_DatesFlexible">My Dates are Flexible</label>
但是,这并不正常工作。结果总是空和 ModelState.IsValid
是假的。
任何人都可以说,我怎么会做这项工作?
Can anyone say how I could make this work?
修改
这是code我结束了,这似乎很好地工作。
This is the code I ended up with, which appears to work fine.
@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")
标签正确与复选框相关联,以便单击文本将切换复选框。
The label is correctly associated with the checkbox so that clicking the text will toggle the checkbox.
推荐答案
这样呢?
模型:
public class MyViewModel
{
public ViewModel2 RDP { get; set; }
}
public class ViewModel2
{
public bool? DatesFlexible { get; set; }
}
控制器:
public ActionResult TestBool()
{
return View(new MyViewModel { RDP = new ViewModel2() });
}
[HttpPost]
public ActionResult TestBool(MyViewModel vm)
{
return View();
}
查看:
@model mvc_testing_2.Models.MyViewModel
@using (Html.BeginForm())
{
@Html.CheckBox("RDP.DatesFlexible",
Model.RDP.DatesFlexible != null && (bool)Model.RDP.DatesFlexible)
<input type="submit" value="go" />
}
这篇关于渲染可空布尔的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!