0

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

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

2 Answers 2

3

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

<input type="checkbox" name="Calendars" value="<%= c.ID %>" checked="checked" /><%= c.Name %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was over complicating it!
2

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) %>

Comments

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.