我有一个StartController,其中包含存储库中的电影列表。我想使用该列表,不仅在StartController中,而且在我的GenreController中,但我无法弄清楚如何。 这是我的StartController:
namespace IMDB
{
public class StartController : Controller
{
// GET: Start
public ActionResult Index()
{
var movies = GetMoviesFromRepository();
return View(movies);
}
// GET: Details
public ActionResult Movie(int id)
{
var allMovies = GetMoviesFromRepository();
var movie = allMovies.FirstOrDefault(x => x.MovieID.Equals(id));
return View(movie);
}
private List<Movie> GetMoviesFromRepository()
{
var movies = new List<Movie>();
var movie1 = new Movie();
movie1.MovieID = 1;
movie1.Title = "Terminator";
movie1.Genre = "Comedy";
movie1.Year = 1984;
movie1.Country = "America";
movie1.Picture = "http://vignette4.wikia.nocookie.net/tvdatabase/images/8/89/Terminator_(1984).jpg";
movies.Add(movie1);
var movie2 = new Movie();
movie2.MovieID = 2;
movie2.Title = "Terminator 2: Judgement Day";
movie2.Genre = "Romantic";
movie2.Year = 1991;
movie2.Country = "America";
movie2.Picture = "https://upload.wikimedia.org/wikipedia/en/8/85/Terminator2poster.jpg";
movies.Add(movie2);
return movies;
}
}
}
这是GenreController,我想从StartController访问列表:
namespace IMDB.Controllers
{
public class GenreController : Controller
{
// GET: Genre
public ActionResult Genre(string genre)
{
var allGenres = GetMoviesFromRepository();
// Some code goes here
return View();
}
}
}
显然这不起作用。但我无法弄清楚如何让我的列表在GenreController中工作。
答案 0 :(得分:2)
这就是Div所说的:
将电影资源库逻辑从控制器中提取出来并放入自己的类中。它的目的是检索你的电影。
public class MovieRepository {
public List<Movie> GetMoviesFromRepository()
{
var movies = new List<Movie>();
var movie1 = new Movie();
movie1.MovieID = 1;
movie1.Title = "Terminator";
movie1.Genre = "Comedy";
movie1.Year = 1984;
movie1.Country = "America";
movie1.Picture = "http://vignette4.wikia.nocookie.net/tvdatabase/images/8/89/Terminator_(1984).jpg";
movies.Add(movie1);
var movie2 = new Movie();
movie2.MovieID = 2;
movie2.Title = "Terminator 2: Judgement Day";
movie2.Genre = "Romantic";
movie2.Year = 1991;
movie2.Country = "America";
movie2.Picture = "https://upload.wikimedia.org/wikipedia/en/8/85/Terminator2poster.jpg";
movies.Add(movie2);
return movies;
}
}
然后在您的控制器中添加一个构造函数,该构造函数初始化将保存您的MovieRepository的私有变量。然后,在您想要检索电影收藏的任何地方,只需调用movieRepository.GetMoviesFromRepository()。
public class StartController : Controller {
private readonly MovieRepository movieRepository;
public StartController()
{
this.movieRepository = new MovieRepository();
}
// GET: Start
public ActionResult Index()
{
var movies = movieRepository.GetMoviesFromRepository();
return View(movies);
}
// GET: Details
public ActionResult Movie(int id)
{
var allMovies = movieRepository.GetMoviesFromRepository();
var movie = allMovies.FirstOrDefault(x => x.MovieID.Equals(id));
return View(movie);
}
}