我有一个复选框,我想在与称为公共的字段相关的视图上显示该复选框,该复选框基本上说明特定行是否是公共的。在数据库中,这是一个位字段,但由于表以前的工作方式,它允许为空。
我正在使用 Html.CheckBoxFor 但它抱怨这个字段,因为在系统中它不是 bool 类型,而是 bool?类型。我想要做的是拥有它,以便如果字段值为空,那么它在前端被视为错误(不幸的是更新数据库值本身不是一个选项)。
我尝试使用 GetValueOrDefault,并按照以下方式在模型文件中添加默认值:
public class Model
{
public bool? Public { get; set; }
public SearchModel()
{
Public = false;
}
}
然而它抱怨这一点,给了我以下错误:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
所以我不确定如何从这里取得进展,有人可以帮助我指出正确的方向吗?
EDIT:
这是我试图用来显示复选框的视图上的代码。在本例中,我添加了一些额外的 html 属性,以便它显示为切换而不是简单的复选框:
Html.CheckBoxFor(model => model.Public, new {data_toggle = "toggle", data_off = "No", data_on = "Yes", data_size = "small"})