如何将可为 null 的 bool 绑定(bind)到 MVC 2 中的复选框。我尝试在 View 中使用以下代码:
<%: Html.CheckBoxFor(model => model.Communication.Before)%>
但是显示编译错误。
提前致谢。
最佳答案
我知道这个问题。您可以尝试使用此解决方法:
在您的 ViewModel 中创建名为 Before 的新属性:
public class YoursViewModel
{
public Communication Communication { get; set; }
public bool Before
{
get
{
bool result;
if (this.Communication.Before.HasValue)
{
result = (bool)this.Communication.Before.Value;
}
else
{
result = false;
}
return result;
}
set
{
this.Communication.Before = value;
}
}
}
此外,您还必须小心通信属性,该属性必须在使用前实例化。例如,当您在 Controller 中初始化 ViewModel 时,您还必须初始化此属性。
ControllerAction()
{
YoursViewModel model = ViewModelFactory.CreateViewModel<YoursViewModel >("");
model.Communication = new Communication ();
return View(model);
}
谢谢 伊万·巴耶夫
关于asp.net - 将 CheckBoxFor 绑定(bind)到 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5019792/