asp.netasp.net-mvc-2c#-4.0

Bind CheckBoxFor to bool?


How to bind nullable bool to checkbox in MVC 2. I try with this code in view:

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

But show me compilation error.

Thanks in advance.


Solution

  • I know about this issue. You can try to use this workaround:

    Create new property called Before in yours 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;
            }
        }
    }
    

    Also you have to be careful for Communication property this have to be instanced before use. For example when you initialize ViewModel in controller you also have to initialize this property.

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

    Thanks Ivan Baev