Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 781
sushiBite Avatar asked Nov 16 '11 13:11

sushiBite


2 Answers

Remove the @ and prefix with a semicolon ie.

intVariable += item.MyNumberOfInteres;
like image 149
Dan Diplo Avatar answered Nov 15 '22 19:11

Dan Diplo


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.

like image 24
Darin Dimitrov Avatar answered Nov 15 '22 19:11

Darin Dimitrov