Simple increment of a local variable in views in ASP.NET MVC3 (Razor)

后端 未结 5 912
借酒劲吻你
借酒劲吻你 2020-12-09 07:37

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 docum

相关标签:
5条回答
  • 2020-12-09 07:54

    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>
    
    0 讨论(0)
  • 2020-12-09 07:55

    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>....
    }...
    
    0 讨论(0)
  • 2020-12-09 07:58
    @{
        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
    
    0 讨论(0)
  • 2020-12-09 08:05

    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>
    
    0 讨论(0)
  • 2020-12-09 08:15

    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.

    0 讨论(0)
提交回复
热议问题