0

I have a CheckBoxFor for a bool? field in a view, however it is underlining it with red saying:

cannot implicitly convert bool? to bool, are you missing a cast

problem is, this is in a lambda:

bool? nullable {get; set;}
CheckBoxFor(m => m.nullable)

If it wasn't a lambda, I know I can do:

(bool)nullable

but I'm not sure how to do this in a lambda to get rid of this error. I tried to do

CheckBoxFor(m => m.nullable.value) 

but this doesn't seem to be retaining its value in the controller, I'm getting a null value back.

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

1 Answers1

2

CheckBoxFor(m => m.nullable ?? false) should achieve your objective.

neontapir
  • 4,698
  • 3
  • 37
  • 52
  • Did you test this? I think there are specific requirements for the expression provided to CheckBoxFor. How will MVC map this back to the `nullable` property? Does it do a deep verification of the expression tree? Will this cause the expression to always be false in the returned object on post? – Bas May 22 '15 at 16:57
  • I guess `CheckBoxFor(m => m.HasValue ? m.Value : false)` could be preferrable. – heltonbiker May 22 '15 at 16:57
  • @heltonbiker `m.GetValueOrDefault()` does that for us. – Bas May 22 '15 at 16:58
  • @Bas, no, I didn't test this. When I was doing a lot of MVC programming, I used to use the nullable operator this way. You're right, in some use cases, it might not be the best approach. – neontapir May 22 '15 at 16:58
  • `GetValueOrDefault` is the approach used by the answer I noted as a possible duplicate. For a Boolean, these two approaches should be equivalent. – neontapir May 22 '15 at 16:59
  • @bas right, but only because default for `bool` is false. But right, your comment's code is much more compact ;) – heltonbiker May 22 '15 at 17:00