[HttpPost] // the other method will be for GET requests, this one will be for POST (the form data will come back as a POST) public IActionResult Create(MovieViewModel viewModel) { if (!ModelState.IsValid) { // there was a server-side validation error - return the user a new // form with what he put in. return(View(viewModel)); } // model binding: // when action methods have parameters, the framework tries to fill them with data // converting types and such, based on the property names matching the form field names. // server-side validation // in the action method where you receive form data (or any data, e.g. query string params) // you need to validate that with logic here. // ASP.NET helps us with this with DataAnnotations // and ModelState object, with model binding // client-side validation // when possible, the form page itself, in front of the user, should stop him // from entering bad data (like with HTML validation attributes, or JS) // ASP.NET helps us with this with DataAnnotations // and jQuery Unobtrusive library and HTML validation attrs // (with the help of tag helpers) var movie = new Movie { Title = viewModel.Title, ReleaseYear = viewModel.ReleaseYear }; try { _movieRepo.AddMovie(movie); } catch (ArgumentException ex) { //ModelState.AddModelError("Title", "title error"); // empty string for "key" means, it's overall model error ModelState.AddModelError("", ex.Message); return(View(viewModel)); } // if we did "return View", the URL bar would still say "Create" //return View("Index", _movieRepo.GetMovies.......) return(RedirectToAction(nameof(Index))); // tell the browser to make a new GET request // to the Index action. }
public ActionResult Create([Bind("Title,Director,Description,Duration_Movie")] Movie movie) { if (ModelState.IsValid) { try { // TODO: Add insert logic here _movieRepo.AddMovie(movie); return(RedirectToAction(nameof(Index))); } catch (Exception ex) { ModelState.AddModelError("", "Create is unable to save"); Console.WriteLine(ex); return(View()); } } else { return(View()); } }
public void AddMovie(Movie movie) { _repository.AddMovie(movie); }