Lesson Sunday

In the last lesson, we updated our controller code to return a List of Items. In this lesson, we're ready to update our view to properly display that List. In the process, we'll cover adding loops and conditionals to a view.

Let's start by updating our Index.cshtml so it can loop through Items. Since Razor supports inline C#, we can add a standard C# foreach loop.

Views/Home/Index.cshtml
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My To-Do List!</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  </head>
  <body>
    @using ToDoList.Models;

    <h1>To Do List</h1>
    <ul>
      @foreach (Item item in Model)
      {
        <li>@item.Description</li>
      }

    </ul>
    <a href="/items/new">Add a new item.</a>
  </body>
</html>

Note that we start with a using directive. We can do this in the view as long as it's prefaced with the usual @. We'll cover why we need this in a moment.

Next, we put a foreach loop inside an unordered list. We specify that we will loop through each item of type Item in Model. We need the using directive so we can declare that item is of type Item. If we didn't have the using directive, we'd need to declare item with the more generic var like this: var item in Model, which isn't ideal.

Finally, we wrap each items Description in an li tag.

This looks exactly like a C# loop other than the fact that we use @ and we intersperse HTML elements with inline C#.

Let's also add a conditional. If a user doesn't have any items in the list yet, there will be a message that says so.

Views/Home/Index.cshtml
...
<h1>To Do List</h1>

@if (Model.Count == 0)
{
  <p>There are no items in the list.</p>
}
<ul>
  @foreach (Item item in Model)
  {
    <li>@item.Description</li>
  }
</ul>
...

If Model.Count == 0, our conditional lets the user know the list has no items. Otherwise, it will loop through the list.

Repository Reference

Follow the link below to view how a sample version of the project should look at this point. Note that this is a link to a specific commit in the repository.

Example GitHub Repo for To Do List

Sample Loop and Conditional with Razor

@if (Model.Count == 0)
{
  <p>There are no items in the list.</p>
}
<ul>
  @foreach (Item item in Model)
  {
    <li>@item.Description</li>
  }
</ul>

Lesson 25 of 38
Last updated more than 3 months ago.