Quick MVC2 checkbox question

Posted by kevinmajor1 on Stack Overflow See other posts from Stack Overflow or by kevinmajor1
Published on 2011-01-13T01:59:27Z Indexed on 2011/01/13 2:54 UTC
Read the original article Hit count: 280

Filed under:
|

In order to get my EF4 EntityCollection to bind with check box values, I have to manually create the check boxes in a loop like so:

<p>
    <%: Html.Label("Platforms") %><br />
    <% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
       { %>
           <%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" /><br />
    <% } %>
</p>

It works, but it doesn't automatically populate the group of check boxes with existing values when I'm editing a model entity. Can I fudge it with something like?

<p>
    <%: Html.Label("Platforms") %><br />
    <% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
       { %>
           <%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" checked=<%: Model.GameData.Platforms.Any(p => PlatformID == i) ? "true" : "false" %> /><br />
    <% } %>
</p>

I figure there has to be something along those lines which will work, and am just wondering if I'm on the right track.

EDIT: I'm purposely staying away from MVC's check box HTML helper methods as they're too inflexible for my needs. My check boxes use integers as their values by design.

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about checkboxes