Mark
Mark

Reputation: 7818

ASP.Net MVC Razor Sum and Count functions

Is it possible to use "Sum" within Razor, so you can sum up what has been interated through on the view. ie. my view is like this:

@model IEnumerable<cb2.ViewModels.ResultsVM>
...
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Qualified)
    </td>
  ...
 }

I then want to sum up all of the Qualified in at the bottom of the screen similar to this:

@Model.Qualified.Sum()

But I get the error:

'System.Collections.Generic.IEnumerable<cb2.ViewModels.ResultsVM>' does not contain a definition for 'Qualified'

I thought it would have been easy in Qazor to simply use Sum or Count on a model?

thanks, Mark

Upvotes: 8

Views: 29385

Answers (2)

musefan
musefan

Reputation: 48415

Remember that Model is an IEnumerable<cb2.ViewModels.ResultsVM>, it does not contain a property for Qualified, but each item within the collection does. So you can call Sum directly on the collection and specify the property that you want to sum, namely Qualified...

@Model.Sum(x => x.Qualified)

Upvotes: 4

D Stanley
D Stanley

Reputation: 152566

I think you want:

@Model.Sum(i => i.Qualified)

Qualified is a property of the items within the model, not the model itself.

Upvotes: 25

Related Questions