1

So by default @Html.CheckBoxFor is going to generate a hidden field after the original field, something like

<input name="xxx" id="xxx" type="checkbox" .... data-val="true" value="true"/>
<input name="xxx" type="hidden" value="false"/>

When I do ajax submit with $(form).serialize() the post body would contain two xxx fields if the checkbox is checked. (xxx=true&&xxx=false) This is expected. But then ModelState.IsValid returns false and the error is

System.InvalidOperationException: The parameter conversion from type 'System.Collections.Generic.List`1[System.String]' to type 'System.Boolean' failed because no type converter can convert between these types

How can I fix this??

Update: It is happening to my WebAPI controller, I am doing the regular model binding with

[HttpPost]
public void MyMethod(MyModel model)
{
    if ( !ModelState.IsValid )
        throw new HttpResponseException( HttpStatusCode.BadRequest );
}
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
Steve
  • 11,696
  • 7
  • 43
  • 81
  • If its really an issue, forget about the helper and just output a plain checkbox using `checked="checked"} />`. But how are you binding your model in the controller? I would have thought the default binder would handle this correctly. – Rhumborl Dec 01 '14 at 21:59
  • @Rhumborl that's what I thought too. But it looks like the WebApi binder is not functioning the same way as the MVC one. I am doing public void MyMethod(MyModel model) by the way – Steve Dec 01 '14 at 22:00
  • possible duplicate of [ASP.Net MVC 4's WebAPI does not bind check boxes correctly?](http://stackoverflow.com/questions/11996285/asp-net-mvc-4s-webapi-does-not-bind-check-boxes-correctly) – Rhumborl Dec 01 '14 at 22:16
  • @Rhumborl that question only provided a workaround without providing the reason. I still would like to find out the reason behind it – Steve Dec 01 '14 at 22:30

0 Answers0