Model view controller MVC-@Html.CheckBoxFor

Model view controller MVC-@Html.CheckBoxFor,model-view-controller,checkbox,Model View Controller,Checkbox,我需要一个复选框,但数据库中的基础数据是smallint类型。不确定如何使用该数据类型设置@Html.Checkbox。它抱怨说: 无法将类型“short”隐式转换为“bool” 以下是我的代码: @Html.CheckBoxFor(model => model.HasCycle) 复选框是一个布尔值,表示true或false。如果预期为真/假(1,0),则可能应该将数据库类型设置为bool。如果不想这样做,则必须将int值转换为bool(1,0)如果在数据库中存储布尔值,则应使

我需要一个复选框,但数据库中的基础数据是smallint类型。不确定如何使用该数据类型设置@Html.Checkbox。它抱怨说:

无法将类型“short”隐式转换为“bool”

以下是我的代码:

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

复选框是一个布尔值,表示true或false。如果预期为真/假(1,0),则可能应该将数据库类型设置为bool。如果不想这样做,则必须将int值转换为bool(1,0)

如果在数据库中存储布尔值,则应使用DB类型“bit”而不是smallint(其中0为false,1为true)

否则,您需要首先将model.HasCycle转换为bool。还有,既然它是short类型的?(可空),您也需要处理空值。您可能希望在模型本身中处理这一点,并将模型中的HasCycle公开为bool而不是short。不过,您可能会遇到一些来回的问题,正确的方法是更改数据库类型

从短文转换成短文?对于bool,您可以执行以下操作:

bool hasCycleBool = false;   //if HasCycle is null, this will remain false
if(model.HasCycle != null)
{
    hasCycleBool = Convert.ToBoolean(model.HasCycle);
}

我和你有同样的问题。我们使用smallint来映射数据库中的布尔值,但我们无法更改它

我正在开发一个新的ASP.NET MVC应用程序,基于我们现有的数据库,所以我必须处理这个问题

我采用的解决方案是创建一个非映射布尔属性,以从映射(smallint/short)属性转换为映射(smallint/short)属性。具体如下:

public short AllowMailing { get; set; }

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