Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox for nullable boolean

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?

like image 930
DMulligan Avatar asked Jul 27 '11 19:07

DMulligan


People also ask

How do you check if a Boolean is nullable?

(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 { .... }

What is a nullable Boolean?

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.


2 Answers

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()) 
like image 139
DMulligan Avatar answered Sep 17 '22 13:09

DMulligan


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'

like image 24
resnyanskiy Avatar answered Sep 21 '22 13:09

resnyanskiy