The foreach
, for, and while loops are available in Razor page syntax in ASP.NET. We can use them to generate pages and write HTML for each individual element in collections.
With the while loop, we usually will need to set up an iteration variable. This can be done with a separate block of code before the loop.
This Razor page uses many code statements and comments—it first uses 3 loops, and then it shows a block of C# code that is accessed from the loops.
foreach
-loop. The property can also be accessed as this.Birds
, with the instance "this."for
-loop is also available, and it can iterate over a range of indexes. This is helpful when indexes are required.@page "/page" @* Part 1: use foreach razor loop. *@ @foreach (var bird in Birds) { <p>FOREACH: @bird</p> } @* Part 2: use for razor loop. *@ @for (var i = 0; i < Birds.Length; i++) { <p>FOR: @Birds[i]</p> } @* Part 3: to use while, we need to use a preliminary block of code to set up the index variable. *@ @{ var w = Birds.Length - 1; } @while (w >= 0) { <p>WHILE: @Birds[w]</p> w--; } @* Part 4: a code block can contain code that is referenced from the razor loops. *@ @code { public string[] Birds { get { return ["mockingbird", "parrot", "sparrow"]; } } }
With loops in ASP.NET Blazor pages, we can access C# code fields, including methods and properties. We can print out values enclosed in HTML tags with minimal formatting issues.