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.

1
  • what is the type of your isHot property? Commented May 7, 2010 at 7:25

3 Answers 3

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

I think the code above will work for you

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried this situation .It passes on building time but it raises the same error message on runtime.
<%=Html.CheckBoxFor(model => model.isHot.HasValue ? model.isHot.Value : false, new {@class="input" })%>
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.

Comments

1

Try

(model=>(bool)model.isHot)

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.