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.

user576510
  • 5,777
  • 20
  • 81
  • 144

2 Answers2

1

Instead of CheckBoxFor use

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

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

  • Thanks @Stephen but cant do UI change. – user576510 Oct 04 '14 at 01:49
  • 1
    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 –  Oct 04 '14 at 01:55
  • If I do something like "" 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 ? – user576510 Oct 04 '14 at 02:06
  • 1
    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` –  Oct 04 '14 at 02:11
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)

Mahesh
  • 567
  • 2
  • 14