Search code examples
razor

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


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!


Solution

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