I have a model which has a boolean property and some other properties that have the DataAnnotations Required attribute.
In my view I have
@Html.CheckBoxFor(model => model.MyProduct.BloodTestEnabled, new { @class = "cb" })
However if the checkbox is not checked the value is false and this gets posted back to the controller with a instance of MyProduct.BloodTestEnabled being false but because it has an instance of MyProduct the ModelState.IsValid equals false because the Required attributes are being caught.
If the checkbox is true I only want it to post back to the controller with a new instance of MyProduct which has been created by the modelbinder.
What I have managed to do is this which fixes it but not sure if its proper:
public class MyViewModel
{
public MyProdct MyProduct
{
get;
set;
}
public bool BloodTestEnabled { get; set; }
}
public ActionResult Add(ProductViewModel newProducts)
{
if (!ModelState.IsValid)
{
return View("HomeIndex", newProducts);
}
//Some other code here
newProducts.MyProduct.BloodTestEnabled = newProducts.BloodTestEnabled;
_basket.AddProduct(newProducts.MyProduct);
}
Simply use an input tag instead. The CheckBoxFor method creates a hidden input that returns a value of True/False. It’s designed to function exactly how you are asking it not to. CheckBoxFor also does not work with lists or non Boolean values.
CheckBoxFor renders like this:
Your code should be something like:
You can test your input here and fine tune the HTML
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_checkbox