My model has a boolean that has to be nullable
public bool? Foo { get; set; }
so in my Razor cshtml I have
@Html.CheckBoxFor(m => m.Foo)
except that doesn't work. Neither does casting it with (bool). If I do
@Html.CheckBoxFor(m => m.Foo.Value)
that doesn't create an error, but it doesn't bind to my model when posted and foo is set to null. Whats the best way to display Foo on the page and make it bind to my model on a post?
(a ?: b) is equivalent to (if (a != null) a else b). So checking a nullable Boolean to true can be shortly done with the elvis operator like that: if ( a ?: false ) { ... } else { .... }
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
I got it to work with
@Html.EditorFor(model => model.Foo)
and then making a file at Views/Shared/EditorTemplates/Boolean.cshtml with the following:
@model bool? @Html.CheckBox("", Model.GetValueOrDefault())
Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:
@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false) @Html.Label("RFP.DatesFlexible", "My Dates are Flexible")
It's like accepted answer from @afinkelstein except we don't need special 'editor template'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With