2016-08-24 60 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) 
相关问题