I am using Razor Pages and I have a table and the field I want to sum is declared as int
public int PunctajGrilaIntrebare { get; set; }
I want to calculate the Sum for all values in the table so I use
var tp = GrilaClassSecondariesList.Sum(s => s.PunctajGrilaIntrebare);
However, the result in the View is 0
When I list the values in the View with
@foreach(var item in Model.GrilaClassSecondariesList)
{
@Html.DisplayFor(m => item.PunctajGrilaIntrebare)
}
I have 0 2 and 4, as stored in the database.
If I use in the View
@Model.GrilaClassSecondariesList.Sum(s => s.PunctajGrilaIntrebare)
I get the sum, 6 but I want to use this in code behind. How do I do this?

Marius VasilePosted Dec 1, 2021, 3:46 PM
Jignesh KumarPosted Dec 1, 2021, 11:57 AM
Method 1 : You can create viewModel and add total field as seperate field and add sum of list in that column,
Method 2 : Create ViewBag and assing total in viewbag and use in razor view
code :
View :