Checkbox for nullable boolean

Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:

@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")

It's like accepted answer from @afinkelstein except we don't need special 'editor template'


I got it to work with

@Html.EditorFor(model => model.Foo) 

and then making a file at Views/Shared/EditorTemplates/Boolean.cshtml with the following:

@model bool?

@Html.CheckBox("", Model.GetValueOrDefault())

I have bool? IsDisabled { get; set; } in Model. Inserted if in View.

<div class="inputClass" id="disabled">
    <div>
    @if(Model.IsDisabled==null)
    {
        Model.IsDisabled = false;
    }           
    @Html.CheckBoxFor(model => model.IsDisabled.Value)         
    </div>
</div> 

My model has a boolean that has to be nullable

Why? This doesn't make sense. A checkbox has two states: checked/unchecked, or True/False if you will. There is no third state.

Or wait you are using your domain models in your views instead of view models? That's your problem. So the solution for me is to use a view model in which you will define a simple boolean property:

public class MyViewModel
{
    public bool Foo { get; set; }
}

and now you will have your controller action pass this view model to the view and generate the proper checkbox.