views:

143

answers:

1

I'm passing a List to an MVC view and generating checkboxes for each object in the list (The checkboxes are named t.Name).

I'd like to be able to tell which checkboxes were checked once the form is posted. However, I'd like to avoid using the FormCollection object. Is there any way to do this?

A: 

Set the name of your checkboxes to something like "MyObject[" + index + "].Checked", and for each checkbox also put a hidden input field named something like "MyObject[" + index + "].Name" with the value set to t.Name.

If you name your fields like that, the default model binder can take your form values and map them to a list of objects with a Name property and a Checked property.

I would try something like the following:

<% foreach(var t in Model)
{ %>
    <div>
        <%= Html.Hidden("MyObject[" + index + "].Name", t.Name, new { id = "MyObject_" + index + "_Name" }) %>
        <%= Html.Checkbox("MyObject[" + index + "].Checked", false, new { id = "MyObject_" + index + "_Checked" }) %>
    </div><%
} %>

I use the anonymous type with id property so that the MVC framework components don't generate HTML elements with invalid id values, but it isn't really necessary.

Your action handling the post would look something like this:

[HttpPost]
ActionResult MyAction(IList<MyObject> objects)
{
    foreach (MyObject obj in objects)
    {
        if (obj.Checked)
        {
            // ...
        }
        else
        {
            // ...
        }
    }

    return View();
}
Dr. Wily's Apprentice