Bind postback data from a strong type view of type List<T>
- by Robert Koritnik
I have a strong type view of type
List<List<MyViewModelClass>>
The outer list will always have two lists of List<MyViewModelClass>. For each of the two outer lists I want to display a group of checkboxes. Each set can have an arbitrary number of choices.
My view model class looks similar to this:
public class MyViewModelClass
{
public Area Area { get; set; }
public bool IsGeneric { get; set; }
public string Code { get; set; }
public bool IsChecked { get; set; }
}
So the final view will look something like:
Please select those that apply:
First set of choices:
x Option 1
x Option 2
x Option 3
etc.
Second set of choices:
x Second Option 1
x Second Option 2
x Second Option 3
x Second Option 4
etc.
Checkboxes should display MyViewModelClass.Area.Name, and their value should be related to MyViewModelClass.Area.Id. Checked state is of course related to MyViewModel.IsChecked.
Question
I wonder how should I use Html.CheckBox() or Html.CheckBoxFor() helper to display my checkboxes? I have to get these values back to the server on a postback of course.
I would like to have my controller action like one of these:
public ActionResult ConsumeSelections(List<List<MyViewModelClass>> data)
{
// process data
}
public ActionResult ConsumeSelections(List<MyViewModelClass> first, List<MyViewModelClass> second)
{
// process data
}
If it makes things simpler, I could make a separate view model type like:
public class Options
{
public List First { get; set; }
public List Second { get; set; }
}
As well as changing my first version of controller action to:
public ActionResult ConsumeSelections(Options data)
{
// process data
}