0

I want to create a checkbox in my MVC site for a particular field, however the field is stored in the model as a byte rather than a bool. So when I try to use CheckBoxFor like

@Html.CheckBoxFor(model => model.type)

it complains that it can't convert from a byte to a bool.

I changed it to instead say:

@Html.CheckBoxFor(model => Convert.ToBoolean(model.type))

But then when running the site I get an error of Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Can someone help or point me to the right place to fix this issue?

James Peel
  • 159
  • 1
  • 3
  • 11
  • Use a [view model](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) with a property which is typeof `bool` and do the conversion on the server (apart from your 2nd example not being able to work, it would never bind when you submit anyway (a `ChexBoxFor()` method submits either `true` or `false`, which would never bind to `byte` –  Aug 31 '16 at 09:16
  • `CheckBoxFor` by design returning boolean value to the respective model, which should converted to byte on server side. Rather than just using a byte property, it is more convenient to use a boolean property to pass into view and keep byte property to hold proper value. – Tetsuya Yamamoto Aug 31 '16 at 09:22
  • @StephenMuecke after creating the view model with the properties I need, where would I do the conversion from bool to byte? Is this done in the model code, or in the controller when I save back the value? – James Peel Aug 31 '16 at 10:14
  • In the controller's GET method where you initialize the view model and map the data model properties to it, and then the reverse in the POST method where you initialize the data model then save the data model –  Aug 31 '16 at 10:16

0 Answers0