How to bind to datatype bit in SQL for Booleans / CheckBoxes in ASP.NET MVC 2 with DataAnnotations

I have a problem with data binding of type boolean to checkbox in MVC 2 data annotations Here's my example code:

label>
Is Hot
</label>
<%=Html.CheckBoxFor(model => model.isHot, new {@class="input" })%>

      

It always brings up this error message below (model => model.isHot).

Cannot convert lambda expression to delegate type 'System.Func<Framework.Models.customer,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type

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

      

Please suggest me how can I solve this problem?

Thanks in advance.

+2


a source to share


3 answers


<%=Html.CheckBoxFor(model => model.isHot ?? false, new {@class="input" })%>

      



I think the code above will work for you

+2


a source


Try



(model=>(bool)model.isHot)

      

+1


a source


Your problem is that Entity Framework has two ways to map a bit data type in SQL to Boolean. If you allow null values ​​in your database then the data type is Nullable, theoretically having 3 values: Null, False, True. This cannot be cleanly compared to Bool, which only has 2 meanings. See here for more details: ASP.net MVC CheckBoxFor checkout error

The simple answer is to go to your database and disallow null values ​​in the bit field.

+1


a source







All Articles