ASP.NET MVC – ViewModel nullable Boolean property in DropDownListFor or CheckBoxFor

Custom Routing and Action Method Names in ASP.NET 5 and ASP.NET MVC 6

In ASP.NET MVC, a ViewModel can be easily defined as a container-type class which represents only the data we want to display on our web page. In any standard MVC-based ASP.NET application, the ViewModel is instantiated by the Controller in response to a GET request using the data fetched from the model. Once built, the ViewModel is passed to the View, where it’s used to populate the page contents/input fields with their property values: this “binding” happens thanks to the   helper methods  available in Razor, such as:

…And so on.

Each one of them gets and sets the ViewModel property given to it in the first parameter, which can be done in the following way:

When the properties are of text and/or numeric types – string, int, double, float and so on – the process it’s pretty much straightforward, expecially if they end up into text boxes using the   or   methods: it’s not that easy when we need to translate a nullable boolean type property (   ) into a    or a  : how to ensure that the values will be properly translated between the ViewModel and the HTML?

For a  , here’s how we can do that:

DropDownListFor with Boolean:
DropDownListFor with Nullable Boolean:
Things get more complicated when dealing with a   scenario, for obvious reasons: as long as have three possible values – true, false and null – there’s no way a   can handle them, since it’s a two-state control. However, we can work around this by creating a non-nullable boolean property and make it act as a proxy, in the following way:

In the ViewModel:
In the View:
The only downside of this workaround is that the null value will be treated as false: if you can’t accept that, it’s better to use a control that can support three states, such as the aforementioned  .

All the above suggestions and workarounds are fully working in MVC 4, MVC5, MVC6 and ASP.NET Core MVC.

Many thanks to this great article written by Brad Wilson for the insights that led me to write this post!



About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies.

View all posts by Ryan