我是靠谱客的博主 要减肥白昼,最近开发中收集的这篇文章主要介绍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

最后

以上就是要减肥白昼为你收集整理的mvc @html.checkbox,MVC - @Html.CheckBoxFor的全部内容,希望文章能够帮你解决mvc @html.checkbox,MVC - @Html.CheckBoxFor所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部