【问题标题】:Cannot implicitly convert type 'bool?' to 'bool' Checkbox MVC无法隐式转换类型“bool?” '布尔'复选框MVC
【发布时间】:2016-08-24 14:54:04
【问题描述】:

我在 MVC 中使用 checkboxes。我有一个表,其中一列为bit 类型。下面的代码给了我一个错误。

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

    ......
}

Chosen 在这里是一个位类型。当我尝试构建它时说:

不能隐式转换类型'bool?' '布尔'。明确的 存在转换(您是否缺少演员表?)

【问题讨论】:

  • x.Chosenbool? 的类型吗?

标签: asp.net-mvc


【解决方案1】:

错误是自我解释的。你的x.Chosenbool? 类型(Nullable&lt;bool&gt;)。

这意味着您应该首先在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"; 
    ......
}

【讨论】:

    【解决方案2】:

    发生这种情况是因为选择字段在您的数据库中可以为空,并且在您的模型中不可为空。为了克服这个

    [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)
    

    【讨论】:

      猜你喜欢
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      相关资源
      最近更新 更多