Checkbox for nullable boolean
My model has a boolean that has to be nullable
public bool? Foo
{
get;
set;
}
so in my Razor cshtml I have
@Html.CheckBoxFor(m => m.Foo)
except that doesn't work. Neither does casting it with (bool). If I do
@Html.CheckBoxFor(m => m.Foo.Value)
that doesn't create an error, but it doesn't bind to my model when posted and foo is set to null. Whats the best way to display Foo on the page and make it bind to my model on a post?
Solution 1:
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())
Solution 2:
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'
Solution 3:
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>
Solution 4:
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.