15

How to calculate a running total?

 2 years ago
source link: https://www.codesd.com/item/how-to-calculate-a-running-total.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to calculate a running total?

advertisements

In foreach in a MVC view, is it possible to calculate a running total of the Amount value?

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.ID)</td>
        <td>@Html.DisplayFor(modelItem => item.Amount)</td>
        <td> // here Item.Amount, should sum based on previous</td>
     </tr>
}

Is it possible here in view or I need any method in controller?


Can you - Yes

@{ decimal runningTotal = 0M; } // assumes Total is typeof decimal
@foreach (var item in Model)
{
    runningTotal += item.Amount
    <tr>
        <td>@Html.DisplayFor(modelItem => item.ID)</td>
        <td>@Html.DisplayFor(modelItem => item.Amount)</td>
        <td>@runningTotal</td>
     </tr>
}

Should you - No

Create a view model to represent what you want to display in the view (i.e. include a public decimal RunningTotal { get; set; } property in addition to properties ID and Amount, and do the calculation in the controller where it belongs, so that in the view its simply

 <td>@Html.DisplayFor(modelItem => item.RunningTotal)</td>

Note this also gives you the flexibility to apply a [DisplayFormat] attribute to format the value in the view.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK