I have a form like this.
<form id="myForm">
<div>
<ul>
<li>
@Html.DropDownListFor(m => m.SelectedVal, new SelectList(Model.ValLst, "Value", "Name"))
</li>
<li>
@Html.TextBoxFor(m => m.Id)
</li>
<li>
@Html.CheckBoxFor(m => m.IsPaid, new { @Id = "IsPaid"})
</li>
</ul>
</div>
</form>
I have to serialize this form as follows & I am operating on the serialized array
values = $('#myForm').serializeArray();
0: Object
name: "SelectedVal"
value: "BMV"
1: Object
name: "Id"
value: "123"
2: Object
name: "IsPaid"
value: "true"
3: Object
name: "IsPaid"
value: "false"
I am facing issue with the CheckBoxFor helper. As, it's creating a hidden field with value false & both hiddenfield & checkbox have the same id. So model value of the checkbox is false always, eventhough it's checked. i.e. while operating on the serialized array, the hidden field value overrides the checkbox value.
So I thought of ignoring hiddenfields while serializing. Like:
values = $('#myForm').find("input[type != 'hidden']").serializeArray();
0: Object
name: "Id"
value: "123"
1: Object
name: "IsPaid"
value: "true"
But, it is not working as I am not getting dropdown value. So, thought,DropDownListFor also uses hidden field. Any suggestion, how to send correct value of checkbox to controller. Something, like ignoring immediate hidden field following checkbox or any other html helper or forcing the hidden field render before the checkbox.
The Checkbox always holds value true & the hidden field holds false always. But, for a checked checkbox, it's parent span holds a class "checked". So, before serializing we can keep the desired value in hidden field. Now, let it override. If the parent span has class 'checked', then keep 'true' in the corresponding hidden field, else false.
// traverse through all the checkboxes, check class of it's parent span
$("input[type='checkbox']").each(function () {
// id of hidden field is same as that of the check box
var hdnFldId = "input[type='hidden']#" + $(this).attr('id');
if ($(this).parent().hasClass('checked'))
{
$(hdnFldId).val(true);
}
else {
$(hdnFldId).val(false);
}
});
values = $('#myForm').serializeArray();