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?
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\"" : "" ) />
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
Seen this issue before and its usually ViewData/ViewBag interference which is a nightmare to debug usually.
You can add a ViewBag.Clear/ViewData.Clear in the function which is giving you an issue.
Cheers,
J