I'm working on modifying Controller logic for two an MVC/Razor generated forms. While debugging my code in order to confirm that my new code is doing what I expected it to do I noticed the following inconsistent behavior.
Form1 defined in Form1.cshtml with ActionResult1 contains a checkbox generated using
@Html.CheckBoxFor(model => model.AttributeName, new Dictionary<string, object>() { { "onclick", "this.checked=!this.checked;" } })
Form2 defined in Form2.cshtml with ActionResult2 contains a checkbox generated using
@Html.CheckBoxFor(model => model.AttributeName)
They both share the same Controller but separate ActionResult methods. The troubling behavior is observed when I submit each form:
When both checkboxes are checked:
When I use the debugging console to see the value for the checkbox in Form1 using
formCollection.GetValue("AttributeName")I see that it contains the string"true,false"therefore returningtruewhen I perform the following convertModel.AttributeName=(bool)formCollection.GetValue("AttributeName").ConvertTo(typeof(bool))When I use the debugging console to see the value for the checkbox in Form2 using
formCollection.GetValue("AttributeName")I see that it contains the string"false,true"therefore returningfalsewhen I perform the following convertModel.AttributeName= (bool)formCollection.GetValue("AttributeName").ConvertTo(typeof(bool))`
Assuming both checkboxes are NOT checked:
- Both forms Form1 and Form2 return the string "false"
This inconsistent behavior is giving me a hard time because I have both ActionResult1 and ActionResult2 use the same following logic after I cast and assign the boolean to Model.AttributeName:
if (Model.AttributeName){ ModelState.AddModelError("AttributeName", "Checkbox is required."); }
Please help.