Asp.net 将CheckBoxFor绑定到bool?

Asp.net 将CheckBoxFor绑定到bool?,asp.net,asp.net-mvc-2,c#-4.0,Asp.net,Asp.net Mvc 2,C# 4.0,如何在MVC2中将可空bool绑定到复选框。我尝试使用以下代码: <%: Html.CheckBoxFor(model => model.Communication.Before)%> model.Communication.Before)%%> 但请告诉我编译错误 提前谢谢。我知道这个问题。您可以尝试使用以下解决方法: 在您的ViewModel中创建以前调用的新属性: public class YoursViewModel { public Communica

如何在MVC2中将可空bool绑定到复选框。我尝试使用以下代码:

<%: Html.CheckBoxFor(model =>  model.Communication.Before)%>
model.Communication.Before)%%>
但请告诉我编译错误


提前谢谢。

我知道这个问题。您可以尝试使用以下解决方法:

在您的ViewModel中创建以前调用的新属性:

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;
        }
    }
}
此外,您还必须注意通信属性,这必须在使用前实例化。例如,在控制器中初始化ViewModel时,还必须初始化此属性

ControllerAction()
{
  YoursViewModel model = ViewModelFactory.CreateViewModel<YoursViewModel >("");
  model.Communication = new Communication ();
  return View(model);
}
ControllerAction()
{
YoursViewModel模型=ViewModelFactory.CreateViewModel(“”);
model.Communication=新通信();
返回视图(模型);
}
谢谢
Ivan Baev

复选框可以有两种状态:已选中/未选中、对/错、1/0。因此,尝试将复选框绑定到可能具有三种状态的属性并不符合实际情况。我建议您调整视图模型,使其使用不可为空的布尔属性。如果在域模型中有一个不能更改的可空布尔值,则可以在域模型和视图模型之间的映射层中执行此操作。

MVC视图中绑定复选框的一种方法

使用EF database first,数据库中的布尔(位)字段会生成一个可为空的布尔值?属性在生成的类中。对于演示,我有一个名为Dude的表,带有字段

  • 唯一标识符
  • 名称varchar(50)
  • 我有点讨厌
以下类由EF生成:

namespace NullableEfDemo
{
 using System;
 public partial class Dude
 {
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<bool> IsAwesome { get; set; }
 }
}
这声明了一个类型为bool的新属性Awesome,可以绑定到编辑视图中的复选框

@Html.CheckBoxFor(model => model.Awesome, new { @class = "control-label" })
在HttpPost中,我绑定的是models Awesome属性,而不是IsAwesome

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Awesome")] Dude dude)
    {…

无法隐式转换布尔?要增强可能重复的注意事项,您可以将
Before
getter简化为一行:
返回此.Communication.Before.GetValueOrDefault()
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Awesome")] Dude dude)
    {…