MVC: Deleting a Record

Deleting Data

Setting Up The Controller

When deleting a record a similar pattern to the Edit Record Example can be followed. There will be two Actions in the controller. The first will display a confirmation message and a hidden the HTML form value of the primary key of the record to be removed. The second Action will delete the record identified by the primary key. Both of these Actions will have the same name but are differentiated by having attributes of HttpGet for the controller showing the blank form, and HttpPost for performing the edit.

The Initial Form

In the Controllers/HomeController add the first action as follows:

CONTROLLER: Controllers/HomeController.cs

This is similiar to the Details Page in that it receives an id parameter via the URL and the routing pattern of localhost:5001/Home/DeleteFilm/2

Adding Links to the Delete Page

The DeleteFilm Controller expects to be sent an id value. We'll do this by editing the AllFilms View.

VIEW: Views/Home/AllFilms.cshtml

Creating the Delete View

Create a View file of Views/Home/DeleteFilm with the following HTML form:

VIEW: Views/Home/DeleteFilm.cshtml

The above creates the form with a hidden field that has the primary key of the record. The user can choose not to delete the record and will simply be linked back to the /Home/AllFilms.

Creating the Action to Delelte the Data

In the controller add the second Action for the httpPost action:

CONTROLLER: Controllers/HomeController.cs

The context updates the model via the Remove method of DbContext and the SaveChanges method of the DbSet is then used to commit the change to the database. The controller then redirects to the AllFilms Action and thus the AllFilms View.