2010-05-07 54 views
2

我有問題,結合數據類型布爾在MVC 2數據註解複選框結合位數據類型 這裏是我的代碼示例:如何在SQL中的布爾/檢查框ASP.NET MVC 2 DataAnnotations

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

它總是在(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?) 

請問我該如何解決這個問題?

在此先感謝。

+0

isHot屬性的類型是什麼? – 2010-05-07 07:25:54

回答

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

我覺得上面的代碼會爲你工作

+0

我試過這種情況。它傳遞構建時間,但它在運行時引發相同的錯誤消息。 – nvtthang 2010-05-08 06:34:36

+0

<%= Html.CheckBoxFor(model => model.isHot.HasValue?model.isHot.Value:false,new {@ class =「input」})%> – anilca 2010-05-08 10:49:23

1

嘗試

(model=>(bool)model.isHot) 
+0

這給了我「模板只能用於字段訪問,屬性訪問,單維數組索引或單參數自定義索引器表達式。「 – SteveCav 2013-07-26 03:20:40

1

你的問題是,實體框架有兩種方式來映射SQL中的bit數據類型爲布爾值。如果你在你的數據庫中允許空值,那麼數據類型是Nullable,它理論上有3個值:Null,False,True。這不能幹淨地映射到只有2個值的Bool。在這裏看到更多的信息:ASP.net MVC CheckBoxFor casting error

簡單的答案是進入你的數據庫,並禁止你的位字段空值。

相關問題