ASP.NET Core: Razor Pages

Deleting Data

Setting Up a New View and Model

In the pages/Films folder, create a new page called DeleteFilm.cshtml. Do so via:

This will create a .cshtml and associated .cs file.

Amending the Model File to Use the Entity Framework

Add a new private readonly variable for the database context.

PAGE MODEL: Pages/Films/DeleteFilm.cshtml.cs

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.

PAGE MODEL: Pages/Films/DeleteFilm.cshtml.cs

Create a Property of type Film named RemoveFilm to hold the current data for the film to be edited.

PAGE MODEL: Pages/Films/DeleteFilm.cshtml.cs

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 Id of the film to be edited.

Link to the DeleteFilm View and passing the Id

We need to edit the route into this page so we know wish Film is to be deleted.

Edit the AllFilms.cshtml to link to the DeleteFilm route and pass the Id as parameter.

The tag-helper asp-route-id is used to do this.

PAGE: Pages/Films/AllFilms.cshtml

Retrieving the Data for the Selected Film

The Id 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.

PAGE: Pages/Films/DeleteFilm.cshtml

Now the Id of the film is been sent to the Page it can be used in the Page Model.

PAGE MODEL: Pages/Films/DeleteFilm.cshtml.cs

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.

PAGE: Pages/Films/DeleteFilm.cshtml

Notice the use of a hidden field which has a tag-helper asp-for to set the Id 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.

PAGE MODEL: Pages/Films/DeleteFilm.cshtml.cs

The above uses dbSet method of Remove to prepare the entity to be deleted which the SaveChanges method then runs.

The Page Model onPost handler has a return type of IActionResult to allow redirection once the data has been updated.