asp.net - 将 CheckBoxFor 绑定(bind)到 bool?

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

如何将可为 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/

相关文章:

asp.net - Logo 未出现在 ASP.net webforms 标题中的某些页面上

asp.net - 新手: MVC3 authentication/remember me

c# - 显示时间填充 Stackoverflow 和 Facebook 是如何做的 - C#

asp.net-mvc - MVC 更新模型如何处理不完整的对象?

c# - 我的屏幕保护程序正在停止屏幕暂停,但我不希望它停止

asp.net - 远程证书被用户验证为无效

.net - 需要图表工具,与 ASP.NET 或 Web 表单兼容

asp.net-mvc-2 - 安装asp.mvc 2 beta nunit项目模板不受信任的组件错误

c# - "If foo isn' t null 在 C# 中有什么好的语法,返回它的属性,否则为 null"

.net - 是类还是结构