Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a variable in outer loop of Razor and use it inside the loop

@{ int i = 0;}
@foreach (var providerInfo in Model.Results)
{
    <div class="row">
      i = i + 1;

Inside the for-each loop I want to have a counter so I tried yo define my variable outside of it as above but Razor doesn't get it! What is the correct Syntax to do this?

like image 908
Bohn Avatar asked Sep 17 '25 23:09

Bohn


1 Answers

In your case statement i = i + 1; is currently interpreted as part of HTML. In order to tell Razor to interpret it as C# code, you can wrap your increment code with a @{ }:

@{ int i = 0;}
@foreach (var providerInfo in Model.Results)
{
    <div class="row">
      @{i = i + 1; }
}
like image 199
dotnetom Avatar answered Sep 22 '25 11:09

dotnetom