CrazyDart
CrazyDart

Reputation: 3801

Set value of var in foreach - Razor View Engine

I hope/suspect this is easy, so I will ask here and make a fool out of my self if it is.

I have a foreach loop in my view, mind you this is a Razor view. I dont know if the ASP.NET View engine does the same... but it might. I want to flip a bool on each loop, but it does not see to let me. The view engine chokes to death. Why? How can I fix it? I did a for loop and I did mod 2 for now, but I really need to understand this.

This is what I tried:

@{
    var IsOdd = false;
}
@foreach(var foo in bar)
{
    @{ IsOdd = !IsOdd; }
    <div class="@(IsOdd ? "odd" : "even")">@foo</div>
}

Upvotes: 2

Views: 8400

Answers (1)

Larsenal
Larsenal

Reputation: 51196

Try this:

@{
    var IsOdd = false;
}
@foreach(var foo in bar)
{
    IsOdd = !IsOdd;
    <div class="@(IsOdd ? "odd" : "even")">@foo</div>
}

(Worked for me with MVC 3 RC.)

Upvotes: 7

Related Questions