0

My code is trying to enumerate over a (currently empty) list of movies. When it gets to the ForEach loop it blows up with the stated error.

I would think it would just not iterate (moveNext()). How can I fix this behavior so that it will just display an empty list when the collection is blank

@using System.Collections.Generic
@using Microsoft.EntityFrameworkCore.Metadata.Internal
@using x.Models
@model IEnumerable<x.Models.Movie>

@{
    ViewData["Title"] = "MovieView";
}

<h2>MovieView</h2>

<p>
    <a asp-action="List">Movie List</a>
</p>
<table class="table">
    <thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Genre)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Year)
        </th>
        <th></th>
    </tr>
    </thead>
    <tbody>
        @foreach (Movie item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Description)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Genre)
                </td>

                <td>
                    @Html.DisplayFor(modelItem => item.Year)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>
JustLearning
  • 3,164
  • 3
  • 35
  • 52
rigamonk
  • 1,179
  • 2
  • 17
  • 45
  • 2
    make sure you create an empty instance of the list before it is sent to the view, So check your controller for the values of the list and make sure it is not null. – JustLearning Jun 28 '16 at 14:45
  • Agree with JustLearning. Probably need to add vm.Movie = new List(); – nurdyguy Jun 28 '16 at 15:06
  • I would lean towards Enumberable.Empty() more than new List(). See http://stackoverflow.com/questions/5319930/which-is-better-enumerable-emptyt-or-new0 – Adam Venezia Jun 28 '16 at 15:09

0 Answers0