将CheckBox绑定到bool?

时间:2011-02-16 17:24:03

标签: asp.net asp.net-mvc-2 c#-4.0

如何在MVC 2中将nullable bool绑定到checkbox。我在视图中尝试使用此代码:

<%: Html.CheckBoxFor(model =>  model.Communication.Before)%>

但是告诉我编译错误。

提前致谢。

3 个答案:

答案 0 :(得分:3)

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

在你的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;
        }
    }
}

此外,您必须小心通信属性,这必须在使用前进行实例化。例如,在控制器中初始化ViewModel时,还必须初始化此属性。

ControllerAction()
{
  YoursViewModel model = ViewModelFactory.CreateViewModel<YoursViewModel >("");
  model.Communication = new Communication ();
  return View(model);
}

由于 伊万巴耶

答案 1 :(得分:2)

复选框可以有两种状态:ckecked / uncheked,true / false,1/0。因此,尝试将复选框绑定到可能具有三种状态的属性并不适合图片。我建议你调整你的视图模型,以便它使用一个不可为空的布尔属性。如果在您的域模型中有一个可以为空的布尔值,您无法更改,则可以在域模型和视图模型之间的映射层中执行此操作。

答案 2 :(得分:1)

在MVC视图中绑定Checkbox的一种方法

首先使用EF数据库,数据库中的布尔(位)字段会产生可空的bool?生成的类中的属性。对于演示,我有一个名为Dude的表,其中包含字段

  • Id uniqueidentifier
  • 名称varchar(50)
  • IsAwesome位

以下类由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; }
 }
}

为了能够将IsAwesome绑定到复选框,我只需要扩展Dude类。这是为了避免编辑生成的类,如果我需要刷新它。所以我在我的项目中添加了一个代码文件 DudePartial.cs (名称无关紧要)。不要忘记声明或使用项目命名空间:

namespace NullableEfDemo
{
 partial class Dude
 {
    public bool Awesome
    {
        get { return IsAwesome ?? false; }
        set { IsAwesome = value; }
    }
  }
}

这声明了一个类型为bool的新属性 Awesome ,可以绑定到编辑视图中的复选框

@Html.CheckBoxFor(model => model.Awesome, new { @class = "control-label" })

在HttpPost中我将模型绑定为Awesome属性而不是IsAwesome。

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