@{
var counter = 1;
foreach (var item in Model.Stuff) {
... some code ...
@{counter = counter + 1;}
}
}
我也试过@{counter++;}
只是为了踢而无效=)如果有人能开导我,我会很感激。谢谢!
答案 0 :(得分:65)
@{
int counter = 1;
foreach (var item in Model.Stuff) {
... some code ...
counter = counter + 1;
}
}
说明:
@{
// csharp code block
// everything in here is code, don't have to use @
int counter = 1;
}
@foreach(var item in collection){
<div> - **EDIT** - html tag is necessary for razor to stop parsing c#
razor automaticaly recognize this as html <br/>
this is rendered for each element in collection <br/>
value of property: @item.Property <br/>
value of counter: @counter++
</div>
}
this is outside foreach
答案 1 :(得分:19)
我没有发现这里的答案在c#中非常有用 - 所以这里有一个工作示例,任何人来到这个页面寻找c#示例:
@{
int counter = 0;
}
@foreach(Object obj in OtherObject)
{
// do stuff
<p>hello world</p>
counter++;
}
简单地说,正如我们已经在@foreach中一样,我们不需要将增量放在任何@ {}值中。
答案 2 :(得分:8)
如果你需要做的就是显示编号,一个更加清晰的解决方案是一次性递增和返回:
@{
var counter = 0;
}
<section>
@foreach(var hat in Ring){
<p> Hat no. @(++counter) </p>
}
</section>
答案 3 :(得分:3)
请参阅以下代码,了解ASP.NET中视图中局部变量的增量,这对我来说很好用。
var i = 0;
@foreach (var data in Model)
{
i++;
<th scope="row">
@i
</th>....
}...
答案 4 :(得分:2)
另一种干净的方法是:
<div>
@{int counter = 1;
foreach (var item in Model)
{
<label>@counter</label>
@Html.ActionLink(item.title, "View", new { id = item.id })
counter++;
}
}
</div>