Hi I am wondering how do I add numbers without displaying them while in foreach loop expamle:
嗨我想知道如何在foreach循环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
欢呼sushiBite
2 个解决方案
#1
19
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.
请记住:视图仅用于显示以视图模型的形式从控制器传递的数据。如果一个视图开始计算变量和东西它不再像一个视图,而是意大利面条代码。
#2
15
Remove the @ and prefix with a semicolon ie.
用分号删除@和前缀即。
intVariable += item.MyNumberOfInteres;
#1
19
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.
请记住:视图仅用于显示以视图模型的形式从控制器传递的数据。如果一个视图开始计算变量和东西它不再像一个视图,而是意大利面条代码。
#2
15
Remove the @ and prefix with a semicolon ie.
用分号删除@和前缀即。
intVariable += item.MyNumberOfInteres;