Reputation: 34129
In my ASP.NET MVC application i have a model with boolean property
public class MyModel
{
[DisplayName("Inherit")]
public bool IsInherit{get;set;}
}
razor view
<form id="myform">
@Html.CheckBoxFor(x=>x.IsInherit)
</form>
This will render html page as ( assuming IsInherit
is true)
<form id="myform">
<input name="IsInherit" id="IsInherit" type="checkbox" checked="checked" value="true" data-val-required="The Inherit field is required." data-val="true">
<input name="IsInherit" type="hidden" value="false">
</form>
When check box is selected and if i serialize the form using jQuery $("#myform").serialize()
then the resultant string is
IsInherit=true&IsInherit=false
and upon AJAX POST, MVC's databinding correctly sets the model property value to true
as expected.
However, in certain cases, i need to serialize the form as object. And for that i have below custom jquery extension method that serializes the form as object
(function() {
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery)
When i serialize the form using this extension method $("#myform").serializeObject()
the resultant object has IsInherit
property of type array with two values true
and false
and when i AJAX POST the json object to server, the MVC biding does not work. and i get error The Inherit field is required.
How do i fix this issue?
Note that the issue is when check box is checked because when check box is checked serializeObject
method creates property of type array and i guess MVC binding does not know how to bind it.
If check box is not checked then everything works fine
Upvotes: 4
Views: 1768
Reputation: 34129
I modified my javascript and use the bitwise operator |
to set the value if it's boolean
(function () {
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if ((typeof (this.value) === "boolean") ||
(typeof (this.value) === "string" && this.value != undefined && (this.value.toLowerCase() === "true" || this.value.toLowerCase() === "false"))) {
o[this.name] = ((o[this.name] == "true") | (this.value == "true")) ? true : false; //Sets value to true if one of two bits is true
}
else {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery)
Upvotes: 3