Editing Data
Setting Up The Controller
To edit data requires two Actions in the controller. The first will display the HTML form with the current values displayed to allow them to be edited, the second Action will edit the values submitted from the form. As with the Adding Data example , 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/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/Home/UpdateFilm/2.
Once the relevant Film information is extracted it is added to a FilmForm to send to the view.
Adding Links to the Update Page
The UpdateFilm Controller expects to be sent an id value. This is done by the hyperlinks in the Views/CMS/Index.cshtml View.
Creating the Update View
Create a View file of Views/Home/UpdateFilm with the following HTML form:
The above creates the form with the values populated.
Notice how the FilmID is stored as a hidden field as we don't want to be edited.
Creating the Action to Update the Data
In the controller add the second Action for the httpPost action:
The context updates the model via the Update 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 to show the update.
Conditional logic is used to redirect to the View returning the Model as submitted. Validation can be added in the same way as in the Adding Record example.
Challenge: Add validation output to the view. Use the asp-validation-for Tag Helper we saw earlier.