Thursday, March 3, 2016

@Html.CheckBoxFor( ) helper method problem when posting to Controller method with Bind(Include=...) annotation

@Html.CheckBoxFor(model => model.IsDeposit) will generate html
<input type="checkbox" name="IsDeposit" value="true" />
<input type="hidden"   name="IsDeposit" value="false" />
given that IsDeposit is a boolean value. Then the form is submitted to a method in controller such as
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include ="PaymentID,IsDeposit")] Payment payment)
{ . . . }        
The problem is that the checkbox value will always be false whether the checkbox is checked or not.

The cause of this problem seems to be the IsDeposit in the Bind(Include=...) annotation is not handled properly yet in ASP.NET MVC. @Html.CheckBoxFor(..) creates two elements with the same name attribute (checkbox and hidden). Possibly only the hidden element is accepted to the method when Bind(Include=..) is used. I tried including "IsDeposit" twice (for example, Bind[Include=IsDeposit,IsDeposit,,]) just in case, but it did not help.

The best bet is to avoid using the Bind(Include=...) annotation when @Html.CheckBoxFor() helper method is used. Alternatively, you can also create the checkbox element manually yourself instead of using the helper method @Html.CheckBoxFor(). For example,
<input type="checkbox" name="IsDeposit" id="IsDeposit" value="true" />

No comments: