Simple increment of a local variable in views in A

2019-01-22 18:32发布

问题:

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!

回答1:

@{
    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


回答2:

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.



回答3:

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>


回答4:

Another clean approach would be:

<div>
@{int counter = 1;
 foreach (var item in Model)
 {
   <label>@counter</label>
   &nbsp;
   @Html.ActionLink(item.title, "View", new { id = item.id })
   counter++;
 }
}
</div>


回答5:

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>....
}...


标签: razor