Summary of ASP. NET MVC5 official tutorials (11) Detailed description of Details and Delete methods, mvc5details
Summary of ASP. NET MVC5 official tutorials (11) Detailed description of Details and Delete Methods
In this chapter, we will study the automatically generated Details and Delete methods.
Open the Movie controller and find the Details method.
//// GET: /Movies/Details/5public ActionResult Details(Int32 id){ Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie);}
Code First uses the Find method to Find the Movie object to be displayed. If the movie object is null, HttpNotFound () is returned, which is necessary.
Delete and DeleteConfirm Methods
// GET: /Movies/Delete/5public ActionResult Delete(Int32 id){ Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } return View(movie);}//// POST: /Movies/Delete/5[HttpPost, ActionName("Delete")][ValidateAntiForgeryToken]public ActionResult DeleteConfirmed(Int32 id){ Movie movie = db.Movies.Find(id); db.Movies.Remove(movie); db.SaveChanges(); return RedirectToAction("Index");}
The first Delete method does not Delete Movie, but returns the deletion confirmation page. On the confirmation page, an HttpPost request is created to Delete Movie. Deleting a Movie using an HttpGet request opens a security vulnerability.
The method for deleting data is DeleteConfirmed. The following are the definitions of the two methods:
public ActionResult Delete(Int32 id)[HttpPost, ActionName("Delete")][ValidateAntiForgeryToken]public ActionResult DeleteConfirmed(Int32 id)
CLR requires the same method name but different parameters for the refactoring method. However, the two Delete methods we use here all receive an integer parameter. If the method name is the same, it constitutes a syntax error.
There are several solutions to this problem:
The first method is to use different method names. This is also the method used by ASP. net mvc 5 support. However, this method has some minor issues: ASP. NET ing method names through address segments. If you rename the method, the routing usually cannot find the method. The solution is already in the above example, we can add the ActionName ("Delete") feature for the DeleteConfirmed method "). In this way, all POST requests whose URLs contain Delete are allocated to the DeleteConfirmed method.
Another common solution is to use the same name and add an Unused parameter to the POST method. For example, some developers will add a FormCollection type parameter to the POST method, and then do not use this parameter:
public ActionResult Delete(FormCollection fcNotUsed, int id = 0){ Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFound(); } db.Movies.Remove(movie); db.SaveChanges(); return RedirectToAction("Index");}
My official ASP. NET MVC5 tutorials are all completed. In combination, most of my original basic problems can be solved, and I hope this will help you.