tags:

views:

55

answers:

2

Basically I have a set of checkboxes that are dynamically created from view data like so:

<input type="checkbox" name="Calendars" value="<%= c.ID %>" /><%= c.Name %>

The value being the Calendar Id.

I can get what checkbox has been brought back using the FormsCollection its messy but it works!

(There also seems to be a bug with the checkbox helper that renders a hidden field next to the checkbox which means true is actually returned as "true,false"! I can work around this so its not an issue just thought Id mention it)

The problem comes when trying to hook the checkboxes up on an edit page!

I have a schedule class which can have multiple calendars and I want to show which calendars a schedule has by checking them on the edit!

My view is strongly typed but MVC magic can't map this!

Any ideas on whats the best way to do this??

I had tried passing the calendar ids in ViewData and do some inline code to check the appropriate checkbox but this is getting messy!

Thanks!!

UPDATE:

Done this

<%= (Model.Calendars.Where(s => s.ID == c.ID).Select(s => s).Count() > 0) ? "checked=checked" : "" %>

+2  A: 

You need to add "checked" tag manually to every check box:

<input type="checkbox" name="Calendars" value="<%= c.ID %>" checked="checked" /><%= c.Name %>
User
Thanks! I was over complicating it!
Rigobert Song
+2  A: 

You dont need <input type="checkbox" - use Html.Checkbox(). It renders a hidden field next to the checkbox - but it is not a bug. From ASP.NET MVC source, InputExtensions.cs, line 201:

// Render an additional <input type="hidden".../> for checkboxes. This
// addresses scenarios where unchecked checkboxes are not sent in the request.
// Sending a hidden input makes it possible to know that the checkbox was present
// on the page when the request was submitted.

Use this:

<%= Html.CheckBox("Calendars", c.ID) %>
eu-ge-ne
ahh! thanks, that makes complete sense!
Rigobert Song