Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC map to nullable bool in model

With a view model containing the field:

public bool? IsDefault { get; set; }

I get an error when trying to map in the view:

<%= Html.CheckBoxFor(model => model.IsDefault) %>

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

I've tried casting, and using .Value and neither worked.

Note the behaviour I would like is that submitting the form should set IsDefault in the model to true or false. A value of null simply means that the model has not been populated.

like image 901
fearofawhackplanet Avatar asked Jun 14 '10 08:06

fearofawhackplanet


2 Answers

To me, this is a lot better:

<%= Html.CheckBox("IsDefault", Model.IsDefault.HasValue? Model.IsDefault : false) %>
like image 171
vapcguy Avatar answered Oct 04 '22 20:10

vapcguy


The issue is you really have three possible values; true, false and null, so the the CheckBoxFor cannot handle the three states (only two states).

Brad Wilson discusses on his blog here. He uses a DropDownList for nullable booleans.

This StackOverflow question does a much better job of describing the situation than I did above. The downside to the solution is sometimes nullable does not imply false, it should be nullable. An example of this would be filter criteria where you don't want true or false applied.

like image 31
John Ptacek Avatar answered Oct 04 '22 22:10

John Ptacek