Jason Deacon Team : Web Development Tags : Technology Web Development MVC

ASP.NET MVC 5 View Model Collection Binding

Jason Deacon Team : Web Development Tags : Technology Web Development MVC

Sometimes it's necessary to use a collection of complex types within a single MVC view.

An example (kept as simple as possible to illustrate the concept):

public class MyCalendarModel 
{
	public string CalendarName { get; set; }
	public bool IsPublic { get; set; }
	public List CalendarEntries { get; set; }
}

public class CalendarEntryModel 
{
	public string Subject;
	public DateTime Date;
	public string Location;
	public bool Required;
}

So in order to allow the user to see a list of all their calendar entries as form elements and edit any field for each one we can simply loop over each one and use Html.[whatever]For(...) . A simple example:

@model MyCalendarModel

@using (Html.BeginForm()) 
{
	Name: @Html.TextBoxFor(x => x.CalendarName)<br/>
Is Public?: @Html.CheckBoxFor(x => x.IsPublic)<br/><br/>
@for (var i = 0; i < Model.CalendarEntries.Count; i++) { <div class="calendar-entry"> Subject: @Html.TextBoxFor(x => x.CalendarEntries[i].Subject)<br/> Date: @Html.TextBoxFor(x => x.CalendarEntries[i].Date)<br/> Location: @Html.TextBoxFor(x => x.CalendarEntries[i].Location)<br/> Required: @Html.CheckBoxFor(x => x.CalendarEntries[i].Required)<br/> </div> } <input type="submit" value="Save" /> }

Then when the form is posted back, the individual calendar entries will be automatically bound back into the model and you can save them as you normally would.

Easy!