2

I am working with checkboxes in MVC. I have a table with one column as bit type.The following code giving me an error.

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

    ......
}

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

1
  • Is x.Chosen type of bool?? Commented Aug 24, 2016 at 5:22

2 Answers 2

1

Error is self explainary. Your x.Chosen is bool? type (Nullable<bool>).

It mean you should first check it on null. like this for example:

[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"; 
    }

    ......
}

It's even better to write like this:

[HttpPost]
public string Index(IEnumerable<City> cities) 
{ 
    if (!cities.Any(x => x.Chosen.HasValue && x.Chosen.Value))
        return "You did not select any city"; 
    ......
}
Sign up to request clarification or add additional context in comments.

Comments

0

It occurs because the field Chosen is nullable in your database & it is non nullable in your model. To overcome this

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

or else change the field Chosen in your model as nullable. For Ex.

public bool? Chosen { get; set; }

then you can simply use

if (cities.Count(x => x.Chosen) == 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.