繁体   English   中英

如何在 razor 之外使用 razor 声明的变量?

[英]How to use a razor declared variable outside of razor?

我有一个显示产品描述和产品价格的 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>
        }

        @foreach (var product in Model)
        {
            var sum = product.Price++;
        }

        
            <tr>
                <td colspan="2">Total Price:   </td>
            </tr>
      

    </table>

我希望能够在 foreach 之外显示 sum 的值

您可以在代码块中声明一个变量并在 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>

另一种方法是using System.Linq

<tr>
  <td colspan="2">Total Price: @Model.Sum(product => product.Price)</td>
</tr>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM