ElenA
ElenA

Reputation: 78

Setting checkbox values in MVC4

In my HTML code i want to create checkboxes that are readonly and their value depends on a data that a get from the database. Setting the readonly property is fine and so is binding the checkbox with my model. But the value on my model (that came from the database) is integer, not boolean. Currently i'm doing it like this

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

so i am wondering if there is any way to achieve this without the if statement

thank you for any advice

Upvotes: 1

Views: 674

Answers (1)

Chris du Preez
Chris du Preez

Reputation: 539

Know this question is old, but perhaps worth mentioning that perhaps a more elegant way of doing this is by creating a property on your model which does the interpretation of .Property value.

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

and then in your view:

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

Upvotes: 1

Related Questions