Home
Map
foreach, for, while loops (Razor)Use loops in Razor page markup. Iterate over a List with the foreach, for and while loops.
ASP.NET
This page was last reviewed on Jan 4, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 4, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.