Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 287
Mark Avatar asked Jan 10 '14 14:01

Mark


People also ask

Does ASP.NET MVC use Razor pages?

A Razor Page is very similar to the view component that ASP.NET MVC developers are used to. It has all the same syntax and functionality. The key difference is that the model and controller code is also included within the Razor Page itself. It is more an MVVM (Model-View-ViewModel) framework.

What is Razor in MVC What are the main Razor syntax rules?

Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.

What is ASP.NET MVC Razor?

ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

What is @: In Cshtml?

CSHTML files use the @ symbol and Razor reserved directives to transition from HTML markup to C# code. Most CSHTML files are created in Microsoft Visual Studio. Visual Studio provides syntax highlighting and Intellisense code suggestions that help developers create CSHTML files.


2 Answers

I think you want:

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

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

like image 70
D Stanley Avatar answered Sep 20 '22 06:09

D Stanley


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)
like image 38
musefan Avatar answered Sep 21 '22 06:09

musefan