1

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

4
  • What does value means here.... value(i.e. 1,2,3,etc) or check(i.e true or false)..... Commented May 31, 2014 at 13:28
  • 1
    did you try to use Model.Property == 2 instead of Model.Property == 2 ? true : false - should do the same thing. In case if you should check on for "2" Commented May 31, 2014 at 13:30
  • this does actually cut out some extra code. thank you Commented May 31, 2014 at 13:32
  • I am just looking for something like doing everything on the model and not checking anything on the view Commented May 31, 2014 at 13:38

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Views should have as little logic as possible. It better if the logic resides in the model or best if the controller controls the logic.
i totally agree about all the logic part and that's what i was trying to achieve. the way you suggested is fine. i was just looking for an elegant workaround instead of working with the actual values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.