我想计算每个位置的所有产品的价值以及所有位置的总和。
所以看起来像这样
位置1
位置2
位置3
所有位置的所有产品的总价
查看:
<div>
@foreach (var location in ViewBag.Location)
{
<h3><u>@locatie.LocatieName</u></h3>
<div>
<table class="table">
<tr>
<th>@Html.DisplayNameFor(model => model.Product)</th>
<th>@Html.DisplayNameFor(model => model.Quantity)</th>
<th>@Html.DisplayNameFor(model => model.Price)</th>
</tr>
@foreach (var product in Model)
{
if (product.LocationId == location.LocationId)
{
<tr>
<td>@product.Product</td>
<td>@product.Quantity</td>
<td>@product.Price</td>
</tr>
@Model.Sum(i=>i.Price)
}
}
</table>
</div>
}
</div>
控制器:
public ActionResult Worth()
{
ViewBag.Location = db.Location.OrderBy(c => c.LocationName).ToList();
return View(db.Product.Include(c => c.Location).ToList());
}
但是以某种方式它仅计算第一个位置的总和,并在其他表上重复。
答案 0 :(得分:0)
一个简单的解决方法是在正确的位置进行计算:
@foreach (var location in ViewBag.Location)
{
...
@foreach (var product in Model)
{
}
// This filters products by current location, and sums up filtered products
@Model.Where(product => product.LocationId == location.LocationId)
.Sum(i => i.Price)
}
// This does not filter anything and just sum for all products
@Model.Sum(i => i.Price)
但是,请考虑是否要查看视图模型。您正在对数据进行一些平凡的操作,最好在控制器中进行操作,然后向视图中添加相应的字段。
答案 1 :(得分:0)
只需在第二个循环中声明一个double:
您可以这样做
<div>
@foreach (var location in ViewBag.Location)
{
<h3><u>@locatie.LocatieName</u></h3>
<div>
<table class="table">
<tr>
@{
double sumPrice = 0;
}
<th>@Html.DisplayNameFor(model => model.Product)</th>
<th>@Html.DisplayNameFor(model => model.Quantity)</th>
<th>@Html.DisplayNameFor(model => model.Price)</th>
</tr>
@foreach (var product in Model)
{
if (product.LocationId == location.LocationId)
{
<tr>
<td>@product.Product</td>
<td>@product.Quantity</td>
<td>@product.Price</td>
@sumPrice+= produck.Price;
</tr>
@Model.Sum(i=>i.Price)
}
}
</table>
<tr> <td> total price </td> <td> @sumPrice </td> </tr>
</div>
}