问题描述
我正在尝试生成带有标题电影的表,并在下面的行中显示两个电影名称。我想对这个代码进行硬编码,因为我对mvc相当陌生。我有一个电影模型,一个名为moviescontroller的控制器,一个视图以及一个局部视图。当我打开浏览器时,收到以下错误“ CS0103:名称”电影”在当前上下文中不存在 “,我认为这意味着它无法识别我要显示的电影的背景。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication1.Models;
namespace WebApplication1.viewmodels
{
public class MovieListviewmodel
{
//View Model
public Movie Movie { get; set; }
public List<Movie> Movies { get; set; }
}
}
@model WebApplication1.viewmodels.MovieListviewmodel
@*
View for Movies
*@
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Movies</h2>
<table id="movies" class="table table-bordered table-hover">
<thead>
<tr>
<th>Movie</th>
</tr>
<tr>
<td>@movie.Name</td>
</tr>
<tr>
<td>@movie.Name</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using WebApplication1.viewmodels;
namespace WebApplication1.Controllers
{
public class MoviesController : Controller
{
public ActionResult Index()
{
//Action result Index
var movies = new List<Movie>
{
new Movie {Name = "Fast FurIoUs"},new Movie {Name = "Star Wars"}
};
var viewmodel = new MovieListviewmodel
{
Movies = movies,};
return View(viewmodel);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class Movie
{
//Properties for Movie Model
public int Id { get; set; }
public string Name { get; set; }
}
}
解决方法
这是因为范围内没有名为movie
的变量,因此当您尝试使用@movie
访问它时,它会失败,因为它不存在。在视图中访问模型的方法是通过视图的Model
属性访问模型。这是一个循环播放电影的简单示例:
@foreach (var movie in Model.Movies)
{
<p>@movie.Name</p>
}
请注意,foreach
正在使用Model.Movies
访问电影列表。此后,我们现在在范围内有了一个movie
变量,可用于访问每个电影的属性。
因此,您的视图变为:
<table id="movies" class="table table-bordered table-hover">
<thead>
<tr>
<th>Movie</th>
</tr>
</thead>
<tbody>
@foreach (var movie in Model.Movies)
{
<tr>
<td>@movie.Name</td>
</tr>
}
</tbody>
</table>
如下所示: