views:

85

answers:

2

I've seen plenty of examples (NerdDinner, Sanderson's Sports Store, etc.) where a view is bound to a collection of objects. The syntax in the view is usually something like this...

<%@ Page... Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyViewModel>>" %>
...
<% foreach (var myViewModel in Model) { %>

I've also seen plenty of examples of inserts or updates where the controller automatically binds the model parameter to the form elements in the view.

I'm looking for a mix of the two techniques where my view has form elements pertaining to a collection of myViewModels where each myViewModel has 3-4 properties. The intent is to allow the user to enter a set of these in one take.

Assuming this is possible, can anyone help me with the syntax? I can't figure out how to label the form elements to make the binding work.

+2  A: 

The definitive answer is here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

You need to name each field as if it were part of an array: "PropertyName[i]"

Clicktricity
+1  A: 

This is possible through the built-in model binder, but you have to do a little bit of convention-based naming of your form objects. First, your action needs to take a collection:

[HttpPost]
public ActionResult CreateFoos(List<Foo> foos)
{
   // I have a list of the foo objects that were posted
}

And then, in the view, let's say you wanted to make a form for each object:

<% for (int i = 0; i < Model.Count; i++) { %>
    <%: Html.TextBoxFor(x => x[i].Property1) %>
    <%: Html.TextBoxFor(x => x[i].Property2) %>
    <%: Html.TextBoxFor(x => x[i].Property3) %>
<% } %>

Pay attention to how the controls are rendered in the HTML, because in your "create" view, you might want to have a javascript button that allows the user to add another record, and you'll have to increase the index for each additional control. It's not too hard, but I just wanted to warn you to pay attention to the source it actually generates.

Scott Anderson