Site icon Ryadel

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 Html.*For  helper methods  available in Razor, such as:

  • Html.LabelFor
  • Html.TextBoxFor
  • Html.CheckBoxFor
  • Html.EditorFor
  • Html.DropDownListFor

...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 Html.TextBoxFor()  or Html.EditoFor()  methods: it's not that easy when we need to translate a nullable boolean type property (  bool? ) into a  DropDownListFor  or a CheckBoxFor : how to ensure that the values will be properly translated between the ViewModel and the HTML?

For a DropDownListFor , here's how we can do that:

DropDownListFor with Boolean:
DropDownListFor with Nullable Boolean:
Things get more complicated when dealing with a CheckBoxFor  scenario, for obvious reasons: as long as have three possible values - true, false and null - there's no way a CheckBoxFor  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 DropDownListFor .

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!

 

Exit mobile version