I am using Razor Pages and I have a table and the field I want to sum is declared as int
C#
public int PunctajGrilaIntrebare { get; set; }I want to calculate the Sum for all values in the table so I use
C#
var tp = GrilaClassSecondariesList.Sum(s => s.PunctajGrilaIntrebare);However, the result in the View is 0
When I list the values in the View with
Code
@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
Code
@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?


Jignesh KumarRank #91 · 22.9K reputationPosted Dec 1, 2021, 6:57 AM EST
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 :
Marius VasileRank #785 · 2.9K reputationPosted Dec 1, 2021, 10:46 AM EST