0

In a form, I want to add a CheckBox to bind model value back to action. My model column is of type bool?

I tried the following code but getting error "Cannot implecitly convert type bool? to bool"

@Html.CheckBoxFor(m=>m.AccomPublic)

Please help me with correct way of using @HTML.CheckBoxFor.

1

2 Answers 2

1

Instead of CheckBoxFor use

@Html.EditorFor(m=>m.AccomPublic)

This will render a drop down with 3 values (True, False and Not Set)

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

4 Comments

Thanks @Stephen but cant do UI change.
You cant use a checkbox for a nullable bool. A checkbox has 2 states (true and false) where as a nullable bool has 3 states (true, false and null) so you need to change the property to bool, or change the UI to use a dropdown (or 3 radio buttons), or create you own control
If I do something like "<input type="checkbox" name="AccomPublic" checked="@Model.AccomPublic" id="publichospitalasaprivatepatient" />" will it work with model binding ? Actually I tried and it is not working. Clicking or unclicking check-box do not change value in model. Is it expected behavior ?
No it wont work, because unchecked checkboxes do not post back so the only possible values you can recieve is true (checked) or null (not checked so nothing posts back). You can never check for false
0

This error is because of your property is of type nullable i.e. bool? Set your property as public bool nameofproperty{get;set;} And use @Html.checkboxFor(m=>m.nameofproperty)

Comments

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.