nullable bool is being passed to the controller null all the time regardless of the value
- by user1807954
I'm trying to pass a nullable bool to my controller. But when I pass the bool value from my view to the controller, it's being passed null all the time regardless of the value it has in my view.
Here is my view:
@model Cars.Models.Car
@using (Html.BeginForm("Index", "Home", FormMethod.Post,
new { id = "CategoryFormID"})) {
<label>Convertible:</label>
<input type="checkbox" id="ConvertibleID" name="convertible"/>
<button type="submit" name="submit" value="search" id="SubmitID">Search</button>
}
And my controller:
[HttpPost]
public ActionResult Index(bool? convertible){
var cars = from d in db.Car
select d;
if (convertible.HasValue)
{
cars = cars.Where(x => x.Convertible == convertible);
}
return View("SearchResult", cars);
}
I also have other fields such as drop down lists and text fields, but they're being passed flawless. Any help would be really appreciated.
Update:
Thank you for your fast responds. However, I did try giving it a value="True" as you guys suggested. There is only 2 options now: null and true. But my intention is to use nullable bool to have three options: null (when user doesn't touch the checkbox), true(checked) and false(unchecked). I know it sounds not smart and silly, but I'm just trying to figure out how nullable bool is working, and what is the intention of having such a thing in C# (I'm new with C#).
I was wondering if it is possible to do so with just checkbox and without the use of dropdownlist or radio buttons.