I have a field called W2_Sent which is defined as (bit,null)
In my view I have the following which shows it as a checkbox:
<div class="editor-label" style="width: 10em">
@Html.Label("W2 Sent")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.W2_Sent)
@Html.ValidationMessageFor(model => model.W2_Sent)
</div>
If I check it, I get an error
The value ‘checked’ is not valid for W2_Sent
[HttpPost]
public ActionResult Create(Employee emp)
{
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
string s = "error";
}
}
I am able to trap the error within the foreach loop you see above..
Why am I getting value ‘checked’ is invalid though
For displaying checkboxes in forms you should always use
@Html.CheckBox/CheckBoxForinstead of<input type="checkbox" name="gender" />. When you use@Html.CheckBox/CheckBoxForASP.NET MVC generates a hidden field which has a boolean value and that is what will be binded to your model property.When you directly use the html part then browsers posts the value of the field as string “checked” if it is, and in model binding that throws the error.