...

/

Iterations and Code Blocks

Iterations and Code Blocks

In this lesson, we will look at iterating a template snippet over data and forcing the C# syntax mode.

Iterative statements

Razor allows the iteration of a template over a collection of data. The simplest way to do it is by using the foreach statement:

Press + to interact
@foreach(var customer in allCustomers)
{
<!--Template that uses the customer variable -->
...
}

Inside the foreach block, we place a template that uses the variable declared in the foreach. This way, the template is instantiated once for each element in the collection.

At the beginning of the block, Razor is in C# mode, then its HTML mode inside all HTML tags. In other words, all the rules we have seen for conditional statements for determining C# and HTML mode also apply to the foreach statement and to all other iterative statements used in this lesson.

We may use the foreach Razor statement to render all data in a collection with a li list or with an ...

Access this course and 1400+ top-rated courses and projects.