sushiBite
sushiBite

Reputation: 361

Razor: adding variable in loop without displaying it

Hi I am wondering how do I add numbers without displaying them while in foreach loop expamle:

@{ int intVariable = 0; }

@foreach(var item in @Model.Collection)
{
    @(intVariable += item.MyNumberOfInteres) //->how can I calculate this without it being rendered to the website ?

    //some Html code.......
}

Can anybody help ?

cheers
sushiBite

Upvotes: 11

Views: 11499

Answers (2)

Dan Diplo
Dan Diplo

Reputation: 25339

Remove the @ and prefix with a semicolon ie.

intVariable += item.MyNumberOfInteres;

Upvotes: 17

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You replace parenthesis with curly brackets and add a trailing semicolon:

@(intVariable += item.MyNumberOfInteres)

becomes:

@{ intVariable += item.MyNumberOfInteres; }

This being said you shouldn't be doing things like this in a view. If you need to do it, this simply means that your view model is not adapted to your view. So adapt it. This kind of information should have been directly integrated in the view model and calculated in the controller.

Remember: the view is there only to display data that it is being passed from the controller under the form of a view model. If a view begins to calculate variables and stuff it no longer resembles to a view but spaghetti code.

Upvotes: 20

Related Questions