Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC @Html.CheckboxFor submits true,false on form submission

Tags:

asp.net-mvc

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?

like image 269
rwkiii Avatar asked Aug 28 '14 23:08

rwkiii


1 Answers

The problem is how you are consuming the form request variable.

In ASP.NET MVC there's probably never a good reason to use Request.Form or it's variants to consume your request data. You need to make a model or put in an argument for the action.

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

The following copied from this answer.

This isn't a bug, and is in fact the same approach that both Ruby on Rails and MonoRail use.

When you submit a form with a checkbox, the value is only posted if the checkbox is checked. So, if you leave the checkbox unchecked then nothing will be sent to the server when in many situations you would want false to be sent instead. As the hidden input has the same name as the checkbox, then if the checkbox is unchecked you'll still get a 'false' sent to the server.

When the checkbox is checked, the ModelBinder will automatically take care of extracting the 'true' from the 'true,false'

like image 140
The Muffin Man Avatar answered Oct 14 '22 06:10

The Muffin Man