views:

84

answers:

2

I'm looking for a way to set the checked property based on an integer (not boolean in this case) inside an MVC view.

Is it possible to express this inside the view alone? (with our without an html helper is fine w/ me)

+2  A: 

You can use standard if clauses and such directly in the view:

<% if (myInt > 3) { %>
    <input name="checkbox1" type="checkbox" checked="checked">a checked box</input>
<% } else { %>
    <input name="checkbox1" type="checkbox">a non-checked box</input>
<% } %>

Of course, Craig's version will look much nicer in your code... ;)

<%= Html.CheckBox("checkbox1", myInt > 3) %>
<label for="checkbox1">a box that might be checked...</label>

Note that you need the label tag to get a caption for your checkbox - the html helper doesn't give you that for free. Unless of course you use one of the overloads which take an IDictionary of html attributes for an argument...

Tomas Lycken
why is it that I overlook the obvious? Thanks for the quick reply!
Toran Billups
"My" version behaves differently, too. (Works with model binders due to hidden input.)
Craig Stuntz
+1  A: 
<%= Html.Checkbox("CheckboxName", someInt != 0) %>
Craig Stuntz