ASP.NET MVC UI template: how to mix IList model property with EditorFor (m => m.subModel)?

Say you have this:

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

And you do this to display the class:

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

How would you do EditFor (??, "CartItem") in 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 user interface template for the entire class, and not just for the property.

+1
source share
2 answers
 <% for (int count = 0; count < Model.cartItems.Count; count++ ) { %><%= Html.EditorFor(m => m.cartItems[count]) %><% } %> 

Creates form names, for example:

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

Which are tied to the original list view model

+1
source

If your ShoppingCart.ascx model is a ShoppingCart class, you should be able to do

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

All Articles