Well, this is just embarrassing. I can't even figure out a simple increment in one of my views in ASP.NET MVC3 (Razor). I have done searches and it appears that the documentation for Razor is pretty sparse. Here is what I have tried and failed miserably:
@{
var counter = 1;
foreach (var item in Model.Stuff) {
... some code ...
@{counter = counter + 1;}
}
}
I have also tried @{counter++;}
just for kicks and to no avail =) I would appreciate it if someone could enlighten me. Thanks!
@{
int counter = 1;
foreach (var item in Model.Stuff) {
... some code ...
counter = counter + 1;
}
}
Explanation:
@{
// 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
I didn't find the answer here was very useful in c# - so here's a working example for anyone coming to this page looking for the c# example:
@{
int counter = 0;
}
@foreach(Object obj in OtherObject)
{
// do stuff
<p>hello world</p>
counter++;
}
Simply, as we are already in the @foreach, we don't need to put the increment inside any @{ } values.
If all you need to do is display the numbering, an even cleaner solution is increment-and-return in one go:
@{
var counter = 0;
}
<section>
@foreach(var hat in Ring){
<p> Hat no. @(++counter) </p>
}
</section>
Another clean approach would be:
<div>
@{int counter = 1;
foreach (var item in Model)
{
<label>@counter</label>
@Html.ActionLink(item.title, "View", new { id = item.id })
counter++;
}
}
</div>
See Following code for increment of a local variable in views in ASP.NET its work fine for me try it.
var i = 0;
@foreach (var data in Model)
{
i++;
<th scope="row">
@i
</th>....
}...