MVC - @ Html.CheckBoxFor [英] MVC - @Html.CheckBoxFor

查看:186
本文介绍了MVC - @ Html.CheckBoxFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

无法将类型'short?'隐式转换为'bool'

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

代码:

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


推荐答案

如果要在数据库中存储布尔值, 'bit'而不是smallint(其中0将为false,1将为true)。

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

否则,需要先将model.HasCycle转换为bool。此外,因为它是类型短? (nullable),你将需要处理空值。你可能希望在模型本身中处理这个,并且将HasCycle从模型中公开暴露为bool而不是short。仍然,你可能会遇到一些问题来回,正确的方法是更改​​数据库类型。

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

这篇关于MVC - @ Html.CheckBoxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆