2

I've got problem with binding data type boolean to checkbox in MVC 2 data annotations Here's my code sample:

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

It always raise this error message below at (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.

nvtthang
  • 604
  • 2
  • 10
  • 27

3 Answers3

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

I think the code above will work for you

xkcd
  • 2,538
  • 11
  • 59
  • 96
  • I've tried this situation .It passes on building time but it raises the same error message on runtime. – nvtthang May 08 '10 at 06:34
  • 1
    <%=Html.CheckBoxFor(model => model.isHot.HasValue ? model.isHot.Value : false, new {@class="input" })%> – xkcd May 08 '10 at 10:49
1

Try

(model=>(bool)model.isHot)
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • That gave me "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions." – SteveCav Jul 26 '13 at 03:20
1

Your problem is that the Entity Framework has two ways to map the Bit datatype in SQL to Boolean. If you allow null values in your database then the datatype is Nullable which theoretically has 3 values: Null, False, True. This can't be cleanly mapped to Bool which only has 2 values. See more info here: ASP.net MVC CheckBoxFor casting error

The simple answer is to go into your database and disallow null values on your Bit field.

Community
  • 1
  • 1
morphatic
  • 7,677
  • 4
  • 47
  • 61