.. _razor-iteration:
Iterating in a Template
=======================
Let's revisit part of the non-efficient HTML from the introduction, where we
hard-coded coffee options in a list.
.. sourcecode:: html
:linenos:
- French Roast
- Espresso
- Kopi Luwak
- Instant
If we want to add, remove, or edit the list items, we need to go in and change
the individual tags, which is a poor use of our time. Fortunately, there is a
way to streamline the process.
In C#, we use a :ref:`foreach_loop` to iterate through the items in a data
collection.
.. sourcecode:: c#
foreach (type item in items) {
// Code to repeat...
}
.. _razor-foreach:
Razor templates allow us to use a ``foreach`` loop to display items in a
collection.
.. sourcecode:: guess
:linenos:
@foreach (type collectionItem in ViewBag.collectionProperty)
{
- @collectionItem
}
#. The ``@foreach`` loop is initiated inside of a list element (either ```` or ``