Providing Nullable Bool as CheckBox

I am new to WebForms for MVC. Do I have a view model field with type bool? and by default, EditorFor() displays this field as a DropDownList with the "Not set" option. I would prefer to display it as a CheckBox, and if the value is null, just set it to a checkbox.

The name of the field is RFP.DatesFlexible , and so I wrote the following markup in my view:

 <input type="checkbox" id="RFP_DatesFlexible" name="RFP.DatesFlexible" /> <label for="RFP_DatesFlexible">My Dates are Flexible</label> 

But that does not work. The result is always zero, and ModelState.IsValid is false.

Can anyone tell me how I could make this work?

EDIT

This is the code I ended up in, which works fine.

 @Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false) @Html.Label("RFP.DatesFlexible", "My Dates are Flexible") 

The shortcut is correctly linked to the check box, so clicking on the item will be toggled.

+7
asp.net-mvc asp.net-mvc-3
Dec 13 2018-11-11T00:
source share
3 answers

Something like that?

Models:

 public class MyViewModel { public ViewModel2 RDP { get; set; } } public class ViewModel2 { public bool? DatesFlexible { get; set; } } 

Controller:

  public ActionResult TestBool() { return View(new MyViewModel { RDP = new ViewModel2() }); } [HttpPost] public ActionResult TestBool(MyViewModel vm) { return View(); } 

View:

 @model mvc_testing_2.Models.MyViewModel @using (Html.BeginForm()) { @Html.CheckBox("RDP.DatesFlexible", Model.RDP.DatesFlexible != null && (bool)Model.RDP.DatesFlexible) <input type="submit" value="go" /> } 
+5
Dec 13 2018-11-12T00:
source share

Firstly, I think this will help to understand how Html.CheckBox works. This is not quite what you expect. Take a look at the behavior of HTML.CheckBox

To answer your question, the reason your code is not working is because your <input /> requires a binding of value='true' . For example:

 <input type='checkbox' name='RFP.DatesFlexible' value='true' /> 

And add the checked='checked' property if it should be checked.

This is why I usually override the Html.CheckBox method with Html.CheckBox own. The default implementation is just confused.

+1
Dec 13 2018-11-12T00:
source share

I know this is marked as accepted, but I had a similar problem, but I iterated over the subtitles, so I had a problem with the name parameter bool? isOpen

When I used this, it was attached to the ViewModel in the message, but displayed a drop-down list:

 @Html.EditorFor(model => model.Days[i].isOpen) 

This displays a check box, but the values ​​are where null in the message:

 @Html.EditorFor("isOpen", model.Days[i].isOpen ?? false) 

Looking at the processed html, I did this in a view that solved it:

 @Html.CheckBox("Days[" + i +"].isOpen", Model.Days[i].isOpen ?? false) 

I know he knows this a little fast n dirty, but he worked

Hope this helps someone.

0
Nov 26 '15 at 14:00
source share



All Articles