ASP.NET MVC UI Template: How to mix an IList Model property with EditorFor( m => m.subModel)?

心已入冬 提交于 2019-12-13 17:23:39

问题


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:


<% 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




回答2:


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") %>
<% } %>


来源:https://stackoverflow.com/questions/2069658/asp-net-mvc-ui-template-how-to-mix-an-ilist-model-property-with-editorfor-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!