views:

609

answers:

2

Say you have this:

public class ShoppingCart {
    public IList<CartItem> cartItems {get; set; }
}

And you do this to render the class:

<%= EditorFor( m => m.ShoppingCart, "ShoppingCart") %>

How would you do the EditorFor( ??, "CartItem") in the ShoppingCart.ascx? I would think it would look something like this:

<% foreach( CartItem myCartItem in m.cartItems) { 
     %><%= EditorFor( ??, "CartItem")
%><% } %>

The idea here of course is to use a UI template for an entire class, not just a property.

+1  A: 

If the model of your ShoppingCart.ascx is the ShoppingCart class, then you should be able to do

<% foreach (CartItem myCartItem in m.cartItems) { %> <%= EditorFor(m => myCartItem, "CartItem") %> <% } %>

maartenba
MVC will take<input id="mylist[0].Name" /><input id="mylist[0].Address" /><input id="mylist[1].Name" /><input id="mylist[1].Address" />And map them to IList<Customer> mylist.That said, do you create a UI template for Customer, pass an index in the ViewData so it knows which iteration of the IList we are on, and how would you format the id="" for the template? I guess we stop using UI templates to get IList to work?
Dr. Zim
Scott Guthrie talked about MVC 2 RC handing array or collection indexes in EditorFor(m => m.ArrayOfItems[i]). Any idea how to get this to work with a List so that the post maps back to the original object?
Dr. Zim
A: 
<% for (int count = 0; count < Model.cartItems.Count; count++ )
   {                                              %><%= 
      Html.EditorFor(m => m.cartItems[count])      %><%
   } 
%>

Creates form names like:

name="cartItems[0].Name"
name="cartItems[1].Name"
name="cartItems[2].Name"

Which bind back to the original List view model

Dr. Zim