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 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 Delete Confirmation View
In the Controllers/CMSController add the first action as follows:
This is similiar to the Details Page in that it receives an id parameter via the URL and the routing pattern of localhost:5001/CMS/DeleteFilm/2
Adding Links to the Delete Page
The DeleteFilm Controller expects to be sent an id value. This is done by the hyperlinks in the Views/CMS/Index.cshtml View.
Creating the Delete View
Create a View file of Views/CMS/DeleteFilm with the following HTML form:
The above creates the form with a hidden field that has the primary key FilmID of the record. The user can choose not to delete the record and will simply be linked back to the /CMS/Index.
Creating the Action to Delete the Data
In the controller add the second Action for the httpPost action:
The context updates the model via the Remove method of DbSet and the SaveChanges method of the DbContext is then used to commit the change to the database. The controller then redirects to the CMS/Index Action which list all the remaining films.