Level 1 / ASP.NET Core Razor / lesson 4 of 6
Looping over a collection
`@foreach` writes the markup inside its braces once per item. The loop variable only exists inside the block - that scoping is the whole point.
Understand the idea
One template, many elements
@foreach runs the markup inside its block for each item. The loop variable refers to the current item and exists only inside the loop.
Collections are data
Adding another tool should change the collection, not require another hand-written <li>. If the collection is empty, the loop renders no items; plan an empty-state message in a real app.
Meaningful HTML
A <ul> containing <li> elements communicates a list to browsers and assistive technology. The Count property reports the number of items independently of how they are displayed.
Preview - simulated. Not a .NET compiler.
Step 1 of 3
In progressFill the list
Give Tools at least three entries using a collection initializer.
- Tools starts with at least three entries - 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 simulator supports basic collection initializers and loops. It does not load data from a database or check null collections for you.
Try it in a real .NET project
Supply a list of tools from a Razor PageModel, render them with @foreach and <li>, then add an empty-state branch when the list has zero items. Test both an empty and populated list.
Check your understanding
What will @foreach render when the Tools list is empty?
Show the explanation
It renders none of the loop body's <li> elements. The surrounding <ul> can still appear, so a real page should consider an empty-state message.
Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.