我试图在 for each 循环的帮助下显示各种信息。 我为每个循环创建了一个循环,它遍历项目列表。在此列表中还有另一个项目列表。
我的代码是:
@foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
@foreach (OrderItem orderItem in invoice.OrderItems)
{
<tr>
<td>@invoice.Customer.Firstname @invoice.Customer.Lastname</td>
<td>@orderItem.Product.Title </td>
<td>@orderItem.Quantity </td>
<td>@orderItem.Product.Price </td>
<td>@orderItem.TotalPrice</td>
</tr>
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">@invoice.TotalPrice</td>
</tr>
</table>
}
但是,我不希望它显示两次客户姓名。而且我不想让客户独占一行。因此,我尝试将起始标记与客户一起放在 foreach 循环之外,而不是用 <tr>
结束 foreach 循环。标签。所以它看起来像这样:
@foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
<tr>
<td>@invoice.Customer.Firstname @invoice.Customer.Lastname</td>
@foreach (OrderItem orderItem in invoice.OrderItems)
{
<td>@orderItem.Product.Title </td>
<td>@orderItem.Quantity </td>
<td>@orderItem.Product.Price </td>
<td>@orderItem.TotalPrice</td>
</tr>
<tr>
}
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">@invoice.TotalPrice</td>
</tr>
</table>
}
更新的解决方案
我遵循@Ed Plunkett 的明智之言,将本地字符串初始化为空。我创建了一个 if/else 语句来检查是否设置了前一个客户,并在循环结束时初始化了前一个客户的值。
@{string prevCust = null; }
@foreach (Invoice invoice in ViewBag.Invoices)
{
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
@foreach (OrderItem orderItem in invoice.OrderItems)
{
<tr>
@if (prevCust != invoice.Customer.Firstname + invoice.Customer.Lastname)
{
<td>@invoice.Customer.Firstname @invoice.Customer.Lastname</td>
}
else
{
<td></td>
}
<td>@orderItem.Product.Title </td>
<td>@orderItem.Quantity </td>
<td>@orderItem.Product.Price </td>
<td>@orderItem.TotalPrice</td>
</tr>
prevCust = invoice.Customer.Firstname + invoice.Customer.Lastname;
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="border-top">@invoice.TotalPrice</td>
</tr>
</table>
}
最佳答案
我会做穴居人风格:只需创建一个局部变量 String prevCustomerName
,初始化为 null,并在循环 block 的末尾更新它。在循环 block 的开头,如果新客户名称与prevCustomerName
相同, 不要将它插入到该行的 HTML 中。
我喜欢你的原始代码 </tr>\n<tr>
在内循环中,但我花了一分钟时间才弄清楚你在做什么,Razor 似乎完全困惑了。而且您仍然需要使用特殊情况对其进行修改,以在非第一行上添加一个空单元格。如果您无法输入 if
无论哪种方式,做穴居人。
关于C# 对于表中的每个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875313/