在MVC4中设置复选框值

时间:2014-05-31 13:14:22

标签: c# html asp.net-mvc-4

在我的HTML代码中,我想创建只读的复选框,它们的值取决于从数据库获取的数据。设置readonly属性很好,因此将复选框与我的模型绑定。但我的模型(来自数据库)的值是整数,而不是布尔值。目前我正在这样做

@Html.CheckBox("myProperty", Model.Property == 2 ? true : false, new { @onclick = "return false" }) <label>Some text for the label</label>

所以我想知道如果没有if语句

,是否有任何方法可以实现这一点

感谢您的任何建议

1 个答案:

答案 0 :(得分:1)

知道这个问题是陈旧的,但也许值得一提的是,或许更优雅的方法是在模型上创建一个属性来解释.Property值。

class Model //the name of your model
{
    //...
    public int Property { get; set; }
    public bool myProperty {
        get    
        {
            return this.Property == 2;
        }
    }
}

然后在你看来:

@Html.CheckBox("myProperty", Model.myProperty, new { @onclick = "return false" }) <label>Some text for the label</label>