in

DĂ© specialist in .NET trainingen en consultancy

Jo-wen Mei

Handling multiple selections in a MVC form

Ok, I found something really cool today!

I have multiple checkboxes that the user can select, and I was struggling to retrieve the selected values in my controller.

Luckily, mvc offers some great assistence; check out this code:

 
<% using (Html.BeginForm("ShowData", "Home")) {  %>
  <% foreach (var o in ViewData.Model) { %>
    <input type="checkbox" name="selectedObjects" value="<%=o.Id%>">
    <%= o.Name %>
  <%}%>
  <input type="submit" value="Submit" />
<%}%>

 

and all the selected items are available in a typed array!

 

public ActionResult ShowData(Guid[] selectedObjects) {
    foreach (Guid guid in selectedObjects)
{
       

    }
}

 

so, the trick is to use the same name for the controls, and the posted values are automagically put in an array.

Nice :)

Published dec 07 2008, 04:13 by Jo-wen
Filed under:

Comments

No Comments