← All lessons

Level 1 / ASP.NET Core Razor / lesson 5 of 6

Looping over objects

Render a list of objects and read members off the loop variable.

Once the list holds objects instead of strings, the loop variable is an object too. `@park.Name` reads one member of the current item - the same path syntax you already used on `Model`.

Understand the idea

A row has more than one value

Each Park object keeps related fields such as Name and Sites together. The loop variable represents one Park, so @park.Name and @park.Sites belong to the same row.

Prefer typed models

A typed collection makes expected members explicit. In a real Razor Pages project the page model can expose List<Park> or a more specific view model instead of assembling markup strings in C#.

The view scales with the data

Once the template describes one item, adding a third park changes only the collection. This separation becomes more valuable when the items come from a service or database.

15 lines
7 lines

Preview - simulated. Not a .NET compiler.

Oklahoma state parks

Step 1 of 3

In progress

Render each name

Loop over Model.Parks with a variable named park, rendering <li>@park.Name</li>.

  • A @foreach loops over Model.Parks - not done yet
  • The loop body reads @park.Name - not done yet
  • The preview shows Robbers Cave - not done yet

Coach

The checklist above is what decides whether a step is done. The coach only explains; it never grades.

The preview is a simulated Razor renderer, not a compiler. It supports @model, @{ } literal assignments, @Expression, @foreach, @if/@else, @* comments *@, and plain markup with class, id, and title attributes. Anything else is reported as outside the lesson instead of being guessed at.

Where the simulator stops

The simulation handles simple object initializers and property access, not real queries, null navigation, async loading, or paging.

Try it in a real .NET project

Define a Park record or class in an ASP.NET Core project, expose a list of parks from OnGet, and render names and site counts in a list. Add one new Park without touching the .cshtml template.

Check your understanding

If a third Park is added to the collection, why doesn't the view need a third <li> written by hand?

Show the explanation

The @foreach body is the template for every Park. Each iteration reads Name and Sites from the current park object.

Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.