Files
Vidly2/Vidly/Controllers/MoviesController.cs

107 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using Vidly.Models;
using Vidly.ViewModels;
namespace Vidly.Controllers
{
public class MoviesController : Controller
{
private ApplicationDbContext _context;
public MoviesController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult New()
{
var movieGenres = _context.MovieGenres.ToList();
var viewModel = new MovieFormViewModel
{
//Movie = new Movie(),
MovieGenres = movieGenres
};
return View("MovieForm", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Movie movie)
{
if (!ModelState.IsValid)
{
var viewModel = new MovieFormViewModel(movie)
{
MovieGenres = _context.MovieGenres.ToList()
};
return View("MovieForm", viewModel);
}
if (movie.Id == 0)
_context.Movies.Add(movie);
else
{
var movieInDb = _context.Movies.Single(c => c.Id == movie.Id);
// Mapper.Map(customer, customerInDb);
movieInDb.Name = movie.Name;
movieInDb.ReleaseDate = movie.ReleaseDate;
movieInDb.MovieGenreId = movie.MovieGenreId;
movieInDb.NumberInStock = movie.NumberInStock;
}
_context.SaveChanges();
return RedirectToAction("Index", "Movies");
}
[Route("Movies")]
[Route("Movies/Index")]
public ActionResult Index()
{
var viewModel = new MoviesViewModel()
{
Movies = _context.Movies.Include(m => m.MovieGenre).ToList()
};
return View(viewModel);
}
[Route("Movies/Movies/{nr}")]
public ActionResult Movie(int nr)
{
var movie = _context.Movies.Include(c => c.MovieGenre).SingleOrDefault(c => c.Id == nr);
if (movie == null)
return HttpNotFound();
return View(movie);
}
public ActionResult Edit(int id)
{
var movie = _context.Movies.SingleOrDefault(c => c.Id == id);
if (movie == null)
return HttpNotFound();
var viewModel = new MovieFormViewModel(movie)
{
MovieGenres = _context.MovieGenres.ToList()
};
return View("MovieForm", viewModel);
}
}
}