天天看點

mvc @html.checkbox,MVC - @Html.CheckBoxFor

問題

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)

回答1:

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

}

回答2:

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:

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)

來源:https://stackoverflow.com/questions/8086029/mvc-html-checkboxfor