Editing a Record
Setting Up a Page and PageModel
Create a new Page called UpdateFilm.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 EditFilm 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.
We'll also create a Property named Message to be able to feedback to the user.
Use the _db entity to populate EditFilm by calling the Find method of the DbSet. This will require the Id of the film to be edited.
Link to the UpdateDate View Passing the Id
We need to edit the route into this page so we know which Film is to be edited.
Edit the AllFilms.cshtml to link to the Update route and pass the Id as parameter.
The tag-helper asp-route-id is used to do this.
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 UpdateFilm.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 it can be used in the Page Model.
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 EditFilm database context we can create a HTML form using tag-helpers.
Editing the Data to Database
Back in the UpdateFilm.cshtml.cs Page Model file add a OnPost() handler to receive the data from the form of method post.
The above uses dbSet method of Update to update the entity.
The Message property is also updated so that the Page can respond to the user accordingly.
Alternative Functionality: Page Redirects
It may make more sense for your application to redirect users once a successful edit has been made.
This can be done by amending the Page Model such that the onPost handler so that it returns an IActionResult type.
If successful the user is redirected by RedirectToPage() to the AllFilms Page. If unsuccessful the Page() method keeps the user on the same page and delivers the update failure message.