Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 4's WebAPI does not bind check boxes correctly?

I'm incorporating WebAPI into my development and am Posting all form submissions to a WebAPI controller. I've noticed that checkboxes are not getting bound to the model correctly. I have a form using:

@Html.CheckBoxFor(m => m.HasVideo)

It produces a checkbox and a hidden form element. When I check the checkbox (meaning a "true" value), the model binding in my WebAPI Post reflects a false for the HasVideo property. I moved the entire method over to a traditional mvc controller, and the binding works as expected.

Is there a workaround for this, or is there something that I'm missing?

like image 487
Tom Schreck Avatar asked Aug 16 '12 22:08

Tom Schreck


2 Answers

dont use this html helper :

@Html.CheckBoxFor(m => m.HasVideo)

try this instead :

<input id="HasVideo" name="HasVideo" type="checkbox" value="true" @(((Model!=null) && Model.HasVideo) ? "checked=\"checked\"" : "" ) />
like image 128
Chtiwi Malek Avatar answered Oct 24 '22 02:10

Chtiwi Malek


I have seen this too. There isn't much on the web about this, and it should be more documented somewhere. The standard controllers will prefer true over false if it finds both, but the api controllers look like they just uses the last value found.

This page contains some information that might support this hypothesis: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

like image 28
Sprintstar Avatar answered Oct 24 '22 02:10

Sprintstar