6

i have checkbox in my which is like this @Html.CheckBoxFor(model => model.SKUs.Jewish) but my Jewish in database is nullable type so it gives me an error cannot implicitly convert type 'bool?' to 'bool'. how do check my model that it has values then it should show that else not.please help.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
DharaPPatel
  • 12,035
  • 9
  • 31
  • 49
  • @Html.CheckBoxFor(model => model.SKUs.Jewish.HasValue ? (bool)model.SKUs.Jewish : false) – Steve Jun 11 '13 at 10:15
  • ITS GIVING ME AN ERROR :Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. – DharaPPatel Jun 11 '13 at 10:24
  • http://stackoverflow.com/questions/6849774/mvc3-creating-checkbox-for-nullable-boolean – Raphaël Althaus Jun 11 '13 at 13:41

3 Answers3

6

You could use the following:

@Html.CheckBox("SKUs.Jewish", Model.SKUs.Jewish.GetValueOrDefault());

If the value is not set it uses the nullable types default value which is false.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
0

With a nullable type you check if it has a value with thing.HasValue, and get at the actual value using thing.Value.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
0

And finally i solve that problem. If you are using a checkbox; uncheck Allow Nulls option of your field in your DB. That's it!

Can Ürek
  • 641
  • 12
  • 24