0

I am attempting to retrieve the bool value from the CheckBox and assign it to the variable m.IsAdministrator, which is of type bool?:

@Html.CheckBoxFor(m => (bool?)(m.isAdministrator))

However, this syntax gives an error. How can I assign the bool CheckBoxFor return value to a bool??

aBlaze
  • 2,436
  • 2
  • 31
  • 63
  • What is the error? – Rufus L Mar 25 '18 at 19:54
  • @RufusL "Cannot cast from `bool?` to `bool`" from the MVC framework when it tries to compile the view, because it expects [`>>`](https://msdn.microsoft.com/en-us/library/system.web.mvc.html.inputextensions.checkboxfor(v=vs.118).aspx#M:System.Web.Mvc.Html.InputExtensions.CheckBoxFor%60%601%28System.Web.Mvc.HtmlHelper{%60%600},System.Linq.Expressions.Expression{System.Func{%60%600,System.Boolean}}%29) but finds `>>`. – GSerg Mar 25 '18 at 19:57
  • To get a `bool` from a `bool?`, where you want the default value to be `false` if the `bool?` is `null`, then you would use the `.Value` property if `.HasValue` is `true`, otherwise use `false`. You can do this with the `?:` ternary operatory: `bool x = m.isAdministrator.HasValue ? m.isAdministrator.Value : false;` – Rufus L Mar 25 '18 at 19:59
  • 1
    @RufusL It will not work with an MVC binding. Please see the duplicate question. – GSerg Mar 25 '18 at 20:01
  • 1
    A `bool?` has 3 states (`true`, `null` and `false`). A checkbox has only 2 therefore you cannot use a checkbox for a `bool?` Either make the property `bool` or use `EditorFor(m =>m.isAdministrator)` which willl generate a dropdownlist with 3 values –  Mar 25 '18 at 20:15
  • Thanks all for your help. It sounds like @StephenMuecke 's answer is the one that worked. Stephen, if you make that an official answer, I will accept it. – aBlaze Mar 25 '18 at 21:40
  • I have duped it. But its Darin Dimitrov's answer which is the correct one in the dupe. –  Mar 25 '18 at 21:42

1 Answers1

-1
@Html.CheckBoxFor(m => m.isAdministrator.Value)

And be sure to check that it has value before or you'll get exception.

However, using nullable in view model is not a best practice.

Ivan Maslov
  • 168
  • 2
  • 13
  • 1
    This binding will compile, but it makes no sense. The value will be `null` on a `POST`. – GSerg Mar 25 '18 at 19:51