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??

7
  • What is the error? Commented Mar 25, 2018 at 19:54
  • @RufusL "Cannot cast from bool? to bool" from the MVC framework when it tries to compile the view, because it expects <Expression<Func<TModel,bool>>> but finds <Expression<Func<TModel,bool?>>>. Commented Mar 25, 2018 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; Commented Mar 25, 2018 at 19:59
  • 1
    @RufusL It will not work with an MVC binding. Please see the duplicate question. Commented Mar 25, 2018 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 Commented Mar 25, 2018 at 20:15

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

1 Comment

This binding will compile, but it makes no sense. The value will be null on a POST.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.