MVC @ Html.CheckboxFor submits true, false when submitting a form

I am using MVC 5 with EF Code First and have a View model containing bool:

public bool MyCheckbox { get; set; }

I initialize this in my view:

model.MyCheckbox = true;

In view:

@Html.CheckBoxFor(m => m.MyCheckbox)

Which are obtained 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 in the view launches AJAX POST for the controller, where I want to see the value of the checkbox:

bool bValue = Request["MyCheckbox"] == "true";

But the value Request["MyCheckbox"]is "true, false" due to an additional hidden field with name="MyCheckbox".

How to view the value of this flag in the controller with the request ["..."] and understand it (true or false)?

I also have another bool element in the View model, and I use it in a hidden field intentionally. In the model:

bool MyHiddenBool { get; set; }

In the Get controller:

model.MyHiddenBool = true;

In view:

@Html.HiddenFor(x => x.MyHiddenBool)

In the controller (via AJAX POST):

bool AnotherBool = Request["MyHiddenBool"] == "true";

Request["MyHiddenBool"] "True", "False" "true" "false".

bools ?

+4
1

, .

ASP.NET MVC, , Request.Form . .

[HttpPost]
public ActionResult PostedForm(bool myHiddenBool)
{
  //Frameworks model binder will extract the form field into your variable based on the name
}

.

, , Ruby on Rails MonoRail.

, , . , , , false. , , , 'false' .

, ModelBinder "" ", "

+4

All Articles