[英]How to use a razor declared variable outside of razor?
I have a foreach displaying product descriptions and product prices.我有一个显示产品描述和产品价格的 foreach。 i want to be able to sum all of the prices and display them in a data cell.我希望能够汇总所有价格并将它们显示在数据单元格中。 How can i do this?我怎样才能做到这一点?
<table class="table table-striped">
<tr>
<th>Description</th>
<th>Price</th>
</tr>
@foreach (var product in Model)
{
<tr>
<td>@product.Description</td>
<td>@product.Price</td>
</tr>
}
@foreach (var product in Model)
{
var sum = product.Price++;
}
<tr>
<td colspan="2">Total Price: </td>
</tr>
</table>
i want to be able to show the value of sum outside the foreach我希望能够在 foreach 之外显示 sum 的值
You can declare a variable inside a code block and use it in the foreach like so:您可以在代码块中声明一个变量并在 foreach 中使用它,如下所示:
<table class="table table-striped">
<tr>
<th>Description</th>
<th>Price</th>
</tr>
@foreach (var product in Model)
{
<tr>
<td>@product.Description</td>
<td>@product.Price</td>
</tr>
}
@{
var sum = 0;
foreach (var product in Model)
{
sum += product.Price;
}
}
<tr>
<td colspan="2">Total Price: @sum</td>
</tr>
</table>
An alternative could be using System.Linq
.另一种方法是using System.Linq
。
<tr>
<td colspan="2">Total Price: @Model.Sum(product => product.Price)</td>
</tr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.