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?
Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:
It's like accepted answer from @afinkelstein except we don't need special 'editor template'
The cleanest approach I could come up with is to expand the extensions available to
HtmlHelper
while still reusing functionality provided by the framework.I experimented with 'shaping' the expression to allow a straight pass through to the native
CheckBoxFor<Expression<Func<T, bool>>>
but I don't think it's possible.I also faced the same issue. I tried the following approach to solve the issue because i don't want to change the DB and again generate the EDMX.
Complicating a primitive with hidden fields to clarify whether False or Null is not recommended.
Checkbox isn't what you should be using -- it really only has one state: Checked. Otherwise, it could be anything.
When your database field is a nullable boolean (
bool?
), the UX should use 3-Radio Buttons, where the first button represents your "Checked", the second button represents "Not Checked" and the third button represents your null, whatever the semantics of null means. You could use a<select><option>
drop down list to save real estate, but the user has to click twice and the choices aren't nearly as instantaneously clear.The RadioButtonList, defined as an extension named RadioButtonForSelectList, builds the radio buttons for you, including the selected/checked value, and sets the
<div class="RBxxxx">
so you can use css to make your radio buttons go horizontal (display: inline-block), vertical, or in a table fashion (display: inline-block; width:100px;)In the model (I'm using string, string for the dictionary definition as a pedagogical example. You can use bool?, string)
I got it to work with
and then making a Boolean.cshtml in my EditorTemplates folder and sticking
inside.