Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.NET 8 Blazor – Why does razor render display after the for loop?

I’m guessing this is by design; if so, can someone explain why or how this happens? I read docs on Microsoft’s website but found nothing explaining why a for loop behaves this way in a razor file.

When I FOR loop in the razor markup, the variable rendered is the final variable value and not the increment count. Why does it do that?

Markup…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<MudStack>

  @for (int x = 0; x < 5; x++) {

    <MudPaper>

      <MudText Typo="Typo.body1">
        @(x)
      </MudText>

    </MudPaper>
  }

</MudStack>

And the result…
The result of the above markup

5
5
5
5
5

I am expecting to see

0
1
2
3
4
5

>Solution :

Introduce a temporary variable:

<MudStack>

  @for (int x = 0; x < 5; x++) {
    var tmp = x;
    <MudPaper>

      <MudText Typo="Typo.body1">
        @(tmp)
      </MudText>

    </MudPaper>
  }

</MudStack>

If I understand correctly the generated code will produce closure as with simple lambda closure (I assume due to combination with MudBlazor)

I am expecting to see …. 5

Then you will also need to change the loop condition to i <= 5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading