I have a model called Movie
. I am going to create a list of Movies and pass it to the view. Here is the controller code:
[Route("movies")]
public ActionResult AllMovies()
{
var movies = new List<Movie>
{
new Movie {Name = "Sherek"},
new Movie {Name = "Halk"},
new Movie {Name = "detector Gadget "}
};
return View(movies);
}
and here is the view code:
@using vidly.Models
@model List<Movie>
@{
ViewBag.Title = "AllMovies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AllMovies</h2>
<ul>
@foreach (var movie in Model.movies)
{
<li>movie </li>
}
</ul>
The problem is it does not recognize movies
in the list. In line Model.movies
, I face with the error:
Movie does not contain a definition for movies and no extension method movies accepting a first argument of type Movie could be found (are you missing a using directive or an assembly reference?)
You have to change your foreach
statement to this
@foreach (var movie in Model)
{
<li>
movie.Name
</li>
}
尝试将模型从List<Movie>
更改为IEnumerable<Movie>
。
Copy this code to your view , I think it should work
@model List<Vidly.Models.Movie>
@{
ViewBag.Title = "All Movies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AllMovies</h2>
<ul>
@foreach (var movie in Model)
{
<li>@movie.Name</li>
}
</ul>
Thanks to @Stephen Muecke.
I have @model List<Movie>
, which somehow means Model = List<Movie>
. Therefore to achieve each movie in the list I have to do
foreach(var movie in Model)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.