Foreach, Razor. 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.
Example. 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.
Part 1 Here we access the Birds property in a foreach-loop. The property can also be accessed as this.Birds, with the instance "this."
Part 2 The for-loop is also available, and it can iterate over a range of indexes. This is helpful when indexes are required.
Part 3 With a while loop, we often will need an iteration variable—we can declare this in a separate block before the loop.
Part 4 A code block can be used from any loop or code block on the page. Here the Birds property returns an array of strings.
@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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.