shruggernaut shruggernaut - 6 months ago 14
HTML Question

MVC - How to submit two sets of multiple check boxes to controller action?

I have two sets of checkboxes in a form that are both almost identical to this:

<input type="checkbox" value="1" name="Test Course"
checked="checked" />Test Course
<input type="checkbox" value="2" name="Test Course 2" />Test Course 2
<input type="checkbox" value="3" name="Test Course 3" />Test Course 3

The form is generated through Razor. Here's the code:

@using (Html.BeginForm("Save", "Material",
new { id = Model.Material.FirstOrDefault().ID },
FormMethod.Get, new { id = "associationForm" })
Html.RenderPartial("Association/_Course", Model);
Html.RenderPartial("Association/_Track", Model);
<br />
<input type="submit" value="Save" />

The checkboxes are rendered through the two partial views you see in the form.

Right now, the only data being submitted successfully is
new { id = Model.Material.FirstOrDefault().ID }
in the 2nd line of parameters in the
@using() {}

I need to submit both sets of checkboxes as collections so I may iterate through them and perform some database operations. I've never done anything like this before and the only thing stopping me are these check boxes.

How can I submit those values as two separate collections?


To do this, you have to render a collection. I will assume you have two collections in your model, one called Courses, and one called Tracks.

@for(int i = 0; i < collection.Count(); i++ {
    // Boolean property indicating value is selected on your Courses view model submodel
    Html.CheckBoxFor(model => model.Courses[i].CourseSelected); 

Then do the same for your Tracks.


Assuming you have a ViewModel with a List<Course> where Course looks like this:

public class Course {
    public bool CourseSelected {get;set;}
    public string CourseName {get;set;}

You will have to lookup the course based on the index of the checkbox collection. Thus, if Course[0] is set, you need to get the first course based on position. You could also look it up by name, but you will have to include a hidden field to allow it to be posted back to the form containing the name. Otherwise, you will CourseName is going to be null and you will just nave the array with the Booleans bound.