Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MV3 Duplicate Query String Values for CheckBox (true,false for boolean)

I've created a fairly straight forward page with a check box:

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Get))
{
  @Html.CheckBoxFor(x => x.MyCheckBox)
  <input type="submit" value="Go!" />      
}

The URL is populated with the MyCheckBox value twice!? As such:

MyAction?MyCheckBox=true&MyCheckBox=false

It only duplicates the value if the check box is true. If set to false it will only appear once in the query string.

The code above is simplified as I have a couple of drop downs and a textbox on the form which work fine. I don't think there's anything unusual about the code which I've left out from this question.

Has anyone had a similar issue with query string parameters being duplicated?

like image 760
pfeds Avatar asked Nov 14 '11 09:11

pfeds


1 Answers

This behaviour is by design of the checkbox control. The standard HTML checkbox control passes no value if it is not checked. This is unintuitive. Instead, the ASP.Net checkbox control has 2 elements, the standard control which is visible and also a hidden control with a value of 'False'.

Therefore, if the checkbox is not checked, there will be one value passed: False.
If it is checked, there will be two values, True and False. You therefore need to use the following code to check for validity in your code:

bool checkboxChecked = Request.QueryString["MyCheckBox"].Contains("True");
like image 146
Rory McCrossan Avatar answered Oct 06 '22 09:10

Rory McCrossan