Reputation: 5529
I'm struggling with Html.Checkbox in ASP.NET MVC. Imagine an Employee with a repeating group of Children:
alt text http://img220.imageshack.us/img220/7208/deletechildrensnapshotk.png
The "Add Child" button works fine, but I can't reliably use "Delete selected children". I render the checkboxes with this:
<% int i = 0; %>
<% foreach (var item in Model.Children) { %>
<tr>
<td>
<%=Html.CheckBox("childrenToDelete[" + i + "]", false, new {value = item.Name})>
</td>
</tr>
<% i++; %>
<% } %>
Here's how my controller action gets the list of children to delete from a FormCollection:
var childrenToDelete = new List<string>();
UpdateModel(childrenToDelete, "childrenToDelete");
I then create an object using the ViewModel pattern which contains the Employee and a List of Child. I can't figure out why 85% of the time I then throw an exception in the View at the Html.Checkbox line. About 15% of the time, it works fine. The exception is "The parameter conversion from type 'System.String' to type 'System.Boolean' failed." IE then displays:
Of course "Bobby" is not a Boolean, so it fails. Any clue about why Html.Checkbox is trying to use "Bobby" as a Boolean? The same ViewModel works fine for adding children, so I don't think I have an error there.
Upvotes: 1
Views: 922
Reputation: 5529
At long last, I think I figured it out. I didn't realize that Html Helpers get their values from the following locations (quoted from "Pro ASP.NET MVC Framework" by Steven Sanderson):
Since my form is a post-back, my Html Helpers tried to first get their values from ModelState. An example result is "Bobby, false" for when you try to delete Bobby. That likely messes up Html.CheckBox in some way I'm not going to take the time to investigate right now. As @darin points out, a workaround without Html Helpers works just fine.
I couldn't figure this out for the longest time since my Model was correct. I didn't even think to look at ModelState. It probably didn't help that I hadn't yet read the section on validation in Sanderson's book.
Upvotes: 0
Reputation: 1039588
Html.CheckBox helper adds a hidden field to the form. I would suggest you assigning an unique identifier to each element in the Children collection and then have this in your form instead of using the helper:
<% foreach (var child in Model.Children) { %>
<input type="checkbox" name="childrenToDelete" value="<%=child.Id%>" />
<%}%>
And then in your controller action:
public ActionResult DeleteChildren(string[] childrenToDelete)
{
// childrenToDelete array will contain selected ids of children to delete
return View();
}
Upvotes: 4