You need to post your collections back to your controller, so for example, say that you have the following classes, that you use as a model:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public List<Group> Groups { get; set; }
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
}
Then say this is your how you pass the model to your view:
public ActionResult Index()
{
var model = new User
{
Name = "Test",
Groups = new List<Group>
{
new Group {Name = "GROUP1"},
new Group {Name = "GROUP2"}
}
};
return View(model);
}
And is how you're expecting it:
[HttpPost]
public ActionResult Index(User user)
{
// do your thing ...
}
Your view should look something like:
<form action="/" method="post">
<input id="Name" name="Name" type="text" value="Test" /><
<input name="Groups[0].Name" type="text" value="GROUP1" />
<input name="Groups[1].Name" type="text" value="GROUP2" />
<input type="submit" value="Submit" name="Submit" />
</form>
Now if you submit your model will be populated. You can of course use an editor template for the Group
collection just create a view in EditorTemplates
-> `/Shared/EditorTemplates/Group.cshtml' that contains the following:
@model MyApp.Models.Group
@Html.EditorFor(x => x.Name)
Now back in in your Index.cshtml
, you can just do:
@model User
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Name)
@Html.EditorFor(x => x.Groups)
<input type="submit" value="Submit" name="Submit" />
}
Here @Html.EditorFor(x => x.Groups)
will iterate through your collection and create the necessary markup corresponding to the one in the Editor Template.
I hope this helps.