Reputation: 1320
I am currently using javascript to generate HTML for checkboxes however when I go to post the form to my controller which accepts FormCollection
as a parameter.
I then put these values into a dictionary and inspect the value within my dictionary. While other checkboxes only return one value, my autoDiscovery
checkbox returns two which are 'on'
and 'true'
, which doesn't make sense to me.
Here is the rendered HTML
<div class="form-group">
<div class="col-md-10">
<label class="col-md-3 control-label" for="autoDiscovery">
<input id="autoDiscovery" type="checkbox" checked="" data-val="false" name="autoDiscovery">
<input type="hidden" name="autoDiscovery" value="true"> Auto Discovery
</label>
</div>
</div>
and here is the javascript I am using to assign the checkboxes
function AssignCheckbox(variableName, jsonData, caption) {
var checked = jsonData == 1 ? 'checked' : '';
var value = jsonData == 1 ? 'true' : 'false';
return divFormGroupOpening + divOpeningInput +
'<label class="col-md-3 control-label" for="' + variableName + '">' + '<input id="' + variableName + '" type="checkbox" name="' + variableName + '" data-val="false"' + checked + '>' +
'<input type="hidden" value="' + value + '" name="' + variableName + '">' +
' ' + caption +'</label></div></div>';
}
Upvotes: 1
Views: 2484
Reputation:
Inspect the html generated when you use the @Html.CheckBoxFor()
method. It generates
<input type="checkbox" name="autoDiscovery" value="true" ..... />
<input type="hidden" name="autoDiscovery" value="false" />
You need to mimic that. Currently your checkbox element does not have a value attribute so if its checked in the view it will post back "on". And your hidden input value is "true"
so that value posts as well.
Just as important, do not use FormCollection. Post back to a model, or add a parameter in the method - bool autoDiscovery
so the DefaultModelBinder
will correctly set the value to either true
or false
depending on the checked state of the checkbox
Upvotes: 1
Reputation: 12737
You have two input
s with the same exact name
property. Ofcourse you would expect two values
<input id="' + variableName + '" name="' + variableName + '" '>'
<input type="hidden" name="' + variableName + '">'
Upvotes: 2