John Lk
John Lk

Reputation: 185

Calculate numbers inside view

I am trying to add numbers from a loop inside MVC view and display the total value of those numbers. But the code bellow is just adding numbers one beside another not getting calculated. Can you plz tell me how can i make it to calculate all number and display?

@{ var TotalWatch = ""; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += item.NumberOfWatch;
 }
}
@TotalWatch

Upvotes: 0

Views: 744

Answers (1)

hyankov
hyankov

Reputation: 4120

Assuming item.NumberOfWatch is a string, the following should work, but is a bad approach.

@{ var TotalWatch = 0; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += int.Parse(item.NumberOfWatch);
 }
}
@TotalWatch

Instead, you should have a strongly-typed view model, which should be passed to the View, rather than passing data through ViewBag.

e.g.

Your model:

class YourViewModel
  int TotalWatch // sum it here

Your view:

@Model.TotalWatch

Upvotes: 1

Related Questions