简体   繁体   中英

How to use a razor declared variable outside of razor?

I have a foreach displaying product descriptions and product prices. 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

You can declare a variable inside a code block and use it in the foreach like so:

<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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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