当我尝试使用foreach语句输出表时,它输出2条错误,表明MovieViewModel和MovieVM不存在。
这是Index.cshtml文件的一部分:
@foreach (MovieViewModel item in MovieVM)
{
<tr>
<td>@item.MovieName</td>
<td>@item.MovieCategory</td>
<td>@item.MovieYear
<td>@item.MoviePrice</td>
</tr>
}
</table>
这是MoviesController.cs文件的一部分:
List<MovieViewModel> MovieVM = new List<MovieViewModel>
{
new MovieViewModel {
MovieID = movie.MovieID,
MovieName = movie.MovieName,
MovieDescription = movie.MovieDescription,
MoviePrice = movie.MoviePrice,
MovieCategory = movie.MovieCategory,
MovieYear = movie.MovieYear
},
};
return View(MovieVM);
}
它输出关于foreach
的这两个错误:
“类型或名称空间'EmployeeViewModel'在 命名空间“ WebApplication3.Models”(您是否缺少程序集 参考?)”
和
“名称'MovieVM'在当前上下文中不存在”
答案 0 :(得分:2)
您必须在视图中定义模型类型。
@model IEnumerable<MovieViewModel>
@foreach (var item in Model)
{
<tr>
<td>@item.MovieName</td>
<td>@item.MovieCategory</td>
<td>@item.MovieYear</td>
<td>@item.MoviePrice</td>
</tr>
}
答案 1 :(得分:0)
此数据库连接与错误有关吗?
public ActionResult Index()
{
PAPEntities db = new PAPEntities();
MoviesData movie = db.MoviesData.SingleOrDefault(x => x.MovieID == 1);
List<MovieViewModels> MovieVM = new List<MovieViewModels>
{
new MovieViewModels {
MovieID = movie.MovieID,
MovieName = movie.MovieName,
MovieDescription = movie.MovieDescription,
MoviePrice = movie.MoviePrice,
MovieCategory = movie.MovieCategory,
MovieYear = movie.MovieYear
},
};
return View(MovieVM);
}
}