Why is CheckBoxFor producing runtime error
Asked Answered
C

1

12

The field the CheckBox is wired to is nullable.

On my view I get the following error:

Cannot implicitly convert type 'bool?' to 'bool'

<%= Html.CheckBoxFor(model => model.Product.Exclusive) %>

How do I fix it without having to change the database design?

Curmudgeon answered 22/3, 2010 at 8:30 Comment(0)
T
20

Exclusive cannot be Nullable, it makes no sense to the ViewEngine when evaluating the expression. It has to either check or not check the checkbox and also respond with a true or false value. Your model needs to have a bool value but that doesn't mean your database has to know that. You just have to do a translation somewhere between the database and the Model, eg. Model.Exclusive = DAO.Exclusive ?? false.

Without knowing what null represents in your data schema or how you generate your model objects, it's hard to give you a lot more detail than that.

Edit: haven't tested this but you might get away with something as simple as

public bool NoNullExclusive
{
    get { return Exclusive ?? false; }
    set { Exclusive = value; }
}

and replacing

<%= Html.CheckBoxFor(model => model.Product.Exclusive) %>

with

<%= Html.CheckBoxFor(model => model.Product.NoNullExclusive) %>
Tatting answered 22/3, 2010 at 8:46 Comment(2)
I created the property you suggested in a partial class. Would this the best place to make this manipulation?Curmudgeon
If your Product class is auto-generated then yes. If not then either in the class itself or in the mapping from data access object to model.Tatting

© 2022 - 2024 — McMap. All rights reserved.