MVC - @Html.CheckBoxFor

2019-07-18 16:27发布

I need a checkbox but the underlying data is of type smallint in the database. Not sure how to make the @Html.Checkbox with that datatype. It complains saying the following:

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

Here is the code that I have:

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

3条回答
霸刀☆藐视天下
2楼-- · 2019-07-18 16:37

I was having the same problem than you. We use smallint to map boolean values in our database, and we cannot change that.

I am developing a new ASP.NET MVC app, based on our existing database, so I have to deal with this issue.

The solution I adopted, was to create a not mapped boolean property to convert from and to my mapped (smallint / short) property. Like follows:

public short AllowMailing { get; set; }

[NotMapped]
public bool AllowMailingBool
{
    get { return AllowMailing == 1? true : false; }
    set { AllowMailing = value ? (short)1 : (short)0; }
}

It works fine.

查看更多
来,给爷笑一个
3楼-- · 2019-07-18 17:00

If you are storing a boolean value in the database, then you should use the DB type 'bit' instead of smallint (where 0 will be false and 1 will be true).

Otherwise, you will need to first convert model.HasCycle to a bool. Also, since it is of type short? (nullable), you will need to handle null values too. You will probably want to handle this in the model itself, and publicly expose HasCycle from the model as a bool instead of a short. Still, you may run into some problems going back and forth, and the right way to do it is to change the database type.

To convert from a short? to a bool you can do something like:

bool hasCycleBool = false;   //if HasCycle is null, this will remain false
if(model.HasCycle != null)
{
    hasCycleBool = Convert.ToBoolean(model.HasCycle);
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-07-18 17:02

a checkbox is a boolean value, meaning true or false. if you are expecting true/false (1,0) you probably should set the database type to a bool. if you don't want to do this, you will have to convert the int value to a bool (1,0)

查看更多
登录 后发表回答