开发者

Quick MVC2 checkbox question

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].Platf开发者_C百科orm.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.


Close. You'll actually want to modify your server-side code so that the "checked" attribute is not emitted at all unless you want the checkbox to be checked.

checked="true"

or

checked="false"

are technically both invalid HTML. Source.

If you want a checked checkbox, you want to emit:

checked="checked"

Any value in the quotes will actually check the box (including checked="false"), but checked="checked" is considered proper. So, updating your code, just tweak the ternary operator to use checked='checked' or nothing at all.

<%: Model.AllPlatforms[i].Platform.Name %> <input type="checkbox" name="PlatformIDs" value="<%: Model.AllPlatforms[i].Platform.PlatformID %>" <%: Model.GameData.Platforms.Any(p => p.PlatformID == i) ? "checked='checked'" : "" %> /><br />


You're on the right track, but I think you need to modify the snipet to it to

<%: Model.GameData.Platforms.Any(p => PlatformID == i) ? "checked='true'" : string.Empty %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜