Examining the Details and Delete methods?92 of 101 people found this helpful Open the Movie controller and examine the // GET: Movies/Details/5public async Task<IActionResult> Details(int? id){ if (id == null) { return NotFound(); } var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); if (movie == null) { return NotFound(); } return View(movie);} The MVC scaffolding engine that created this action method adds a comment showing a HTTP request that invokes the method. In this case it’s a GET request with three URL segments, the app.UseMvc(routes => { routes.MapRoute( name: 'default', template: '{controller=Home}/{action=Index}/{id?}'); }); Code First makes it easy to search for data using the Examine the Delete and DeleteConfirmed methods. // GET: Movies/Delete/5public async Task<IActionResult> Delete(int? id){ if (id == null) { return NotFound(); } var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); if (movie == null) { return NotFound(); } return View(movie);}// POST: Movies/Delete/5[HttpPost, ActionName('Delete')][ValidateAntiForgeryToken]public async Task<IActionResult> DeleteConfirmed(int id){ var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); _context.Movie.Remove(movie); await _context.SaveChangesAsync(); return RedirectToAction('Index');} Note that the The // GET: Movies/Delete/5public async Task<IActionResult> Delete(int? id)// POST: Movies/Delete/5public async Task<IActionResult> DeleteConfirmed(int id) The common language runtime (CLR) requires overloaded methods to have a unique parameter signature (same method name but different list of parameters). However, here you need two There are two approaches to this problem, one is to give the methods different names. That’s what the scaffolding mechanism did in the preceding example. However, this introduces a small problem: ASP.NET maps segments of a URL to action methods by name, and if you rename a method, routing normally wouldn’t be able to find that method. The solution is what you see in the example, which is to add the Another common work around for methods that have identical names and signatures is to artificially change the signature of the POST method to include an extra (unused) parameter. That’s what we did in a previous post when we added the // POST: Movies/Delete/5[HttpPost][ValidateAntiForgeryToken]public async Task<IActionResult> Delete(int id, bool notUsed){ var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id); _context.Movie.Remove(movie); await _context.SaveChangesAsync(); return RedirectToAction('Index');} |
|