C# Access child members of hierarchy with foreach

2019-03-06 15:23发布

I am trying to make Foreach work for the html razor below. At the end of the day, I want ShoppingCart to be a list of CartLines. I want to get rid of the [0] statement, and make it variable. Any solution or optimal method would help. Feel free to edit the class also.

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 IEnumerable<ShoppingCart>
@foreach (var item in Model)
{
   <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Items[0].Product)
        </td>

2条回答
我只想做你的唯一
2楼-- · 2019-03-06 15:52

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) 
    }
}
查看更多
Ridiculous、
3楼-- · 2019-03-06 16:05

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>
查看更多
登录 后发表回答