I am using MVC 5 with EF Code First and have a View model that contains a bool:
public bool MyCheckbox { get; set; }
I initialize this in my View's get:
model.MyCheckbox = true;
In the View:
@Html.CheckBoxFor(m => m.MyCheckbox)
Which get rendered as:
<input checked="checked" data-val="true" data-val-required="The field is required." id="MyCheckbox" name="MyCheckbox" type="checkbox" value="true" />
<input name="MyCheckbox" type="hidden" value="false" />
One of my Buttons on the View triggers an Ajax POST to the Controller where I want to look at the checkbox value:
bool bValue = Request["MyCheckbox"] == "true";
But the value of Request["MyCheckbox"]
is "true,false" due to the extra hidden field with name="MyCheckbox"
.
How do I view the value of this checkbox in the controller with Request["..."] and make sense of it (either true or false)?
I also have another bool member in the View model and I use it in a hidden field intentionally. In the model:
bool MyHiddenBool { get; set; }
In the Controller Get:
model.MyHiddenBool = true;
In the View:
@Html.HiddenFor(x => x.MyHiddenBool)
In the Controller (via Ajax POST):
bool AnotherBool = Request["MyHiddenBool"] == "true";
But the value of Request["MyHiddenBool"]
is either "True" or "False" instead of "true" and "false".
What gives with this inconsistency and how can I reliably see the values of these two methods of bools in my Views?