Deleting a Record
Setting Up a Page and PageModel
Create a new Page called DeleteFilm.cshtml as done in the previous examples to create a Page and PageModel.
Amending the PageModel File to Use the Entity Framework
Add a new private readonly variable for the database context.
Create a constructor that uses dependency injection to reference the database context. This removes the need to manage a database context object in this file.
Create a Property of type Film named RemoveFilm to hold the current data for the film to be edited.
Note the use of [BindProperty] that enables Model Binding. Model Binding is the process of sending and receiving values via HTTP to the .net application. Model Binding automates the binding of data from HTTP, in this case values from a HTML form.
Use the _db entity to populate RemoveFilm by calling the Find method of the DbSet. This will require the FilmID of the film to be deleted.
Link to the DeleteFilm View Passing the Id
We need to edit the route into this page so we know which Film is to be deleted.
Edit the AllFilms.cshtml to link to the DeleteFilm route and pass the FilmID as parameter.
The tag helper asp-route-id is used to do this.
Retrieving the Data for the Selected Film
The FilmID is now been sent as a querystring. It is neater to hide the querystring to create a more user friendly URL.
Amend the DeleteFilm.cshtml page's @page directive which appears at the very top of the page. Amend it to include a route parameter in this example an int named Id.
Now the Id of the film is been sent to the Page so it can be used in the PageModel.
The above uses dbSet method of Find which takes the primary key as a parameter to search and return a matching entity.
Building the HTML form in the View
Now the Page Model is aware of the RemoveFilm database context we can create a HTML form using Tag Helpers.
Notice the use of a hidden field which has a tag-helper asp-for to set the FilmID of the record to be deleted.
Deleting the Data
Back in the DeleteFilm.cshtml.cs Page Model file at a OnPost() handler to receive the data from the form of method post.
The above uses dbSet method of Remove, as done with the MVC approach, to prepare the entity to be deleted which the SaveChanges method then runs.
The PageModel onPost handler has a return type of IActionResult to allow redirection once the data has been updated.