C# Access child members of hierarchy with foreach

一笑奈何 提交于 2019-12-02 09:34:54

Iterate over your list elements, not your class:

class ShoppingCart
{
    public IList<CartLine> Items { get; } = new List<CartLine>();

    public ShoppingCart() {}
}

public class CartLine
{
    public int CartLineId { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

@model ShoppingCart
@foreach (var item in Model.Items)
{
   <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Product)
        </td>
JohnB

so you are going to need a nested foreach:

@foreach (var cart in Model)
{    
    @foreach (var line in cart.Items )
    {
        @Html.DisplayFor(modelItem => line.Product) 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!