访问控制器的操作视图时出错

时间:2017-01-12 19:30:36

标签: c# asp.net-mvc

我收到此错误“foreach语句无法对'Vidly.Models.Movie'类型的变量进行操作,因为'Vidly.Models.Movie'在此行中不包含'GetEnumerator'的公共定义”@foreach (模型中的var movie)“

我的电影控制器就是这个

public class MoviesController : Controller
    {
        private ApplicationDbContext _context;

        public MoviesController()
        {
            _context = new ApplicationDbContext();
        }

        protected override void Dispose(bool disposing)
        {
            _context.Dispose();
        }
        // GET: Movies
        public ActionResult Index()
        {
            var movie = _context.Movies.Include(m => m.Genre).ToList();
            return View(movie);
        }

        public ActionResult Details(int id)
        {
            var movie = _context.Movies.Include(m => m.Genre).SingleOrDefault(m => m.Id == id);
            if (movie == null)
                return HttpNotFound();
            return View(movie);
        }
    }
}

这是我的索引操作查看实现

@model Vidly.Models.Movie
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Movies</h2>

<table>
    <thead>
        <tr>
            <th>Movie</th>
            <th>Genre</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var movie in Model)    // getting error on this line
        {
            <tr>
                <td> @Html.ActionLink(@movie.Name, "Details", "Movies", new { id = movie.Id}) </td>
                <td>@movie.Genre.Name</td>
            </tr>
        }
    </tbody>
</table>

我还为另一个非常类似于此的控制器实现了另一个动作视图实现,但这并没有导致任何错误...

2 个答案:

答案 0 :(得分:1)

您对视图的模型声明是错误的,它应该是:

start D:\strawberry\perl\bin\perl.exe scriptname.pl 1234 otherparams

答案 1 :(得分:0)

因为您已将视图中的模型定义为单个影片。您的模型需要是可枚举的类型

@model IEnumerable<Vidly.Models.Movie>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Movies</h2>

<table>
    <thead>
        <tr>
            <th>Movie</th>
            <th>Genre</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var movie in Model)    // getting error on this line
        {
            <tr>
                <td> @Html.ActionLink(@movie.Name, "Details", "Movies", new { id = movie.Id}) </td>
                <td>@movie.Genre.Name</td>
            </tr>
        }
    </tbody>
</table>