请解决此错误,MVC复选框选择 [英] Please solve this error, MVC checkboxes selection
问题描述
嗨
我正在使用MVC中的复选框。我有一个表格,其中一个列为bit 类型。以下代码给我错误
我尝试过:
Hi
I am working with checkboxes in MVC.I have a table with one clolumn as "bit" type.The following code giving me erro
What I have tried:
[HttpPost]
public string Index(IEnumerable<city> cities)
{
if (cities.Count(x => x.Chosen) == 0)
{
return "You did not select any city";
}
此处选择的是一种类型。当我试图建立它时说
不能隐式转换类型'bool?' 'bool'。存在显式转换(你是否错过了演员?)
Chosen is a bit type here. and when i am trying to build it says "
Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
推荐答案
对于可以为空的
类型使用价值
属性
Fornullable
Types useValue
property
if (cities.Count(x => x.Chosen.HasValue ? x.Chosen.Value :false) == 0)
你的问题是你选择的属性class city是bool类型的?而不是bool。bool?==一个可以为空的布尔值,在这种情况下你不能像使用它一样使用它是因为值可能为null。
你的一些选择如下:
Your problem is that your Chosen property of class city is of type bool? instead of bool. bool? == a nullable boolean in which case you aren't able to use it like you are due to the possibility of the value being null.
A few of your options are the following.
// This option uses the null coalesing operator and the one i would suggest
if (cities.Count(m => m.Chosen ?? false) == 0)
{
}
//Direct comparison to true
if (cities.Count(m => m.Chosen == true) == 0)
{
}
//Long form version of the first example provided. Checking for HasValue first to prevent null comparison
if (cities.Count(m => m.Chosen.HasValue ? m.Chosen.Value : false) == 0)
{
}
除了解决方案1,你不应该使用计数
如果您只想确定序列是否包含与条件匹配的任何项目。使用任意 [ ^ ]或所有 [ ^ ]而不是:
In addition to solution 1, you shouldn't useCount
if you simply want to determine whether the sequence contains any items that match the condition. Use Any[^] or All[^] instead:
if (!cities.Any(m => m.Chosen == true))
{
...
}
if (cities.All(m => m.Chosen != true))
{
...
}
任何
方法会在找到后立即返回符合条件的元素。
所有
方法将在找到不匹配条件的元素后立即返回。 />
Count
方法总是要枚举整个输入序列。
The Any
method will return as soon as it finds an element that matches the condition.
The All
method will return as soon as it finds an element that doesn't match the condition.
The Count
method will always have to enumerate the entire input sequence.
这篇关于请解决此错误,MVC复选框选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!