2016-08-24 71 views
2

我正在與MVC中的checkboxes。我有一個表,其中一列爲bit type。下面的代碼給我一個錯誤。不能隱式轉換類型'bool?'到'布爾'複選框MVC

[HttpPost] 
public string Index(IEnumerable<City> cities) 
{ 
    if (cities.Count(x => x.Chosen) == 0) 
    { 
     return "You did not select any city"; 
    } 

    ...... 
} 

在這裏選擇是有點類型。當我試圖建立它說:

不能隱式轉換類型'布爾?'到'布爾'。存在明確的 轉換(您是否缺少演員?)

+0

是'x.Chosen' bool類型的'?'? –

回答

1

錯誤是自我說明。您的x.Chosenbool?類型(Nullable<bool>)。

這意味着你應該首先檢查它在null。像這樣的例子:

[HttpPost] 
public string Index(IEnumerable<City> cities) 
{ 
    if (cities.Count(x => x.Chosen.HasValue && x.Chosen.Value) == 0) 
    { 
     return "You did not select any city"; 
    } 

    ...... 
} 

它甚至更好,寫這樣的:

[HttpPost] 
public string Index(IEnumerable<City> cities) 
{ 
    if (!cities.Any(x => x.Chosen.HasValue && x.Chosen.Value)) 
     return "You did not select any city"; 
    ...... 
} 
0

它的發生是因爲現場選的是在你的數據庫&可空它是在你的模型非空。解決此問題

[HttpPost] 
public string Index(IEnumerable<City> cities) 
{ 
    if (cities.Count(x => x.Chosen.Value) == 0) 
    { 
     return "You did not select any city"; 
    } 
} 

否則更改字段在您的模型中選擇爲可爲空。例如。

public bool? Chosen { get; set; } 

,那麼你可以簡單地使用

if (cities.Count(x => x.Chosen) == 0) 
相關問題