我正在尝试使Foreach适用于以下html剃须刀。归根结底,我希望ShoppingCart成为CartLines的列表。我想摆脱[0]语句,并使其可变。任何解决方案或最佳方法都会有所帮助。也可以随时编辑课程。
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>
答案 0 :(得分:2)
所以您将需要一个嵌套的foreach:
@foreach (var cart in Model)
{
@foreach (var line in cart.Items )
{
@Html.DisplayFor(modelItem => line.Product)
}
}
答案 1 :(得分:1)
遍历您的列表元素,而不是您的课程:
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>