Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

asp.net mvc 2 - Why is CheckBoxFor producing runtime error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...