views:

187

answers:

1

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.

+1  A: 

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.

John Ptacek