0

I have following fields Db table , I want populate those values in check boxes

    public Nullable<bool> Report_Users { get; set; }
    public Nullable<bool> Innovation_Discussion_User { get; set; }

this is specific row in above table

enter image description here

I'm expecting ,

  1. empty check box if Values are NULL or FALSE
  2. checked check box if values are TRUE

this is the syntax I've been used ,

            @Html.CheckBox("Report User", Model == null ? false : (Model.Report_Users == Model.Report_Users ? true : false), new { @value = "false"  }) Report User
             &nbsp; 
            @Html.CheckBox("Innovation Discussion User", Model == null ? false : (Model.Innovation_Discussion_User == Model.Innovation_Discussion_User ? true : false), new { @value = "false"  }) Innovation Discussion User

but this seems not poplate correct values,

both check boxes showing checked always

enter image description here

2
  • You cannot use a checkbox for a nullable bool. A checkbox has only 2 states (check/unchecked - or true/false) whereas bool? has 3 states (true/false/null). Make the property bool (not nullable) or use EditorFor(m => m.Report_Users) whicj will generate a dropdownlist with 3 values. Commented Jan 21, 2016 at 10:09
  • @kez Try the follwoing Model?.Report_Users ?? false Commented Jan 21, 2016 at 10:10

2 Answers 2

2

Try the following

@Html.CheckBox("Report User",Model?.Report_Users ?? false)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use GetValueOrDefault() on nullable types, this will return false for null values as false is the default value for a bool.

@Html.CheckBox("Report User", 
    Model.Report_Users.GetValueOrDefault()) Report User

10 Comments

what if Model is null ?
@tchelidze I can't understand why the model would be null in the first place. Can you? :)
Don't set new { @value = "false" } - CheckBox() generates 2 inputs, a checkbox with value="true" and a hidden input with value="false". This code would only ever post back false` no matter if it was checked or not
@hutchonoid have you never had scenario, while developing, where Model is null ? In this case Model.Report_Users can also be null and this will cause NullReference
@tchelidze - .GetValueOrDefault() cannot throw a NullReference - it returns false when the value if null
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.