Tuesday, October 4, 2016

MVC Razor Syntax: Can't implicitly convert bool? to bool

Problem:

My model had several variables which were nullable Booleans.  My issue was how to bind them in the Razor syntax without getting an error.


I had tried
@Html.CheckBoxFor(model=>(bool) model.LengthConfinementLife)


which will compile but fails on a runtime error.


Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Solution:



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


Source:

http://stackoverflow.com/questions/6849774/mvc3-creating-checkbox-for-nullable-boolean

No comments:

Post a Comment