daveaglick / FluentBootstrap

Provides extensions, helper classes, model binding, and other goodies to help you use the Bootstrap CSS framework from .NET code.
http://www.fluentbootstrap.com
MIT License
200 stars 76 forks source link

Model Binding CheckBoxFor #68

Closed dm7777 closed 7 years ago

dm7777 commented 7 years ago

Hi

I am trying to implement model binding for a boolean property in my view model to a check box using the following. Instead of posting a cut down version of my code, I tried this by modifying the example code (FluentBootstrap.Tests.Web solution) in MvcForms.cshtml (MvcTests views folder) and MvcTestsController with the following:

MvcForms.cshtml (I have commented the rest of the markup for convenience) using (var form1 = Html.Bootstrap().Form().HideValidationSummary().Begin()) { @form.EditorFor(x => x.PropB) @form1.CheckBoxFor(x => x.PropD) @form1.Submit("Save").AddCss(" pull-left") }

MvcTestsController [HttpPost] public ActionResult MvcTests (string view, ViewModel vm) { return View(view, vm); }

fbmvc-cbformb-presubmit fbmvc-cbformb-submitiedebugger fbmvc-cbformb-submitvs2013

As you can see PropB comes in corerctly in the controller. However PropD is null even though it is checked and the IE debugger shows this in the request body.

I am using VS 2013, FbMVC v3.3.5.3. I have upgraded my custom project to FbMVC v3.3.5.4 and use MVC 5.2.3, Razor 3.2.3 and web pages 3.2.3

Am I doing something wrong here. Can you please help

By the way your library is excellent. I have been using this for a while now without any issues until I ran into this

Many Thanks in advance

daveaglick commented 7 years ago

I can confirm the same behavior when attempting to bind the postback for the forms example. Not sure if this issue is with the HTML generated by FluentBootstrap, something with the model binder, or something else. Currently investigating.

daveaglick commented 7 years ago

This one was tricky. It turns out that checkboxes don't post back to the server in a reliable way for the model binder to process. In order to hack around this, ASP.NET adds an additional hidden form field for every checkbox that has a default value of false. This becomes the "fallback" for when the real checkbox actually is false. Then when it's actually true, that overrides the hidden field. FluentBootstrap wasn't outputting the necessary hidden field so the binding was getting all messed up. Just committed a fix that'll go out with the next version.

dm7777 commented 7 years ago

Hi Dave

Thanks. I will try out your fix.

Regards