Issue serializing checkbox as boolean property and MVC binding

Viewed 1412

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

1 Answers
Related