In the previous example (Extracting One Record), one record was extracted but we could only stipulate that it would the default or first record in the table. It is much more useful to extract the specific record we are interested in. This is done by passing the primary key of the record we would like the details on. The primary key value will be sent to the controller via the routing.
Previously (Extracting all records) we created a DbContext in Controller/HomeController. As such we don't need to repeat that step here but be aware you will need a DbContext if one has not already been made available to the Controller.
Add a Task/Action to the controller called FilmDetails.
This is very similar to the previous example but does differ in two ways. Firstly, the Action is sent an integer parameter of id. This was defined in the routing in the Startup.cs.
We have already seen how the Controller and Action work in the pattern. The third part of the pattern is the id value. This is a value (a querystring value) that feeds a parameter into the action.
| URL Called | Contoller Called | Action / Method Called | View Used |
|---|---|---|---|
| localhost:5001/Home/FilmDetails/456 | Controllers/HomeController.cs | FilmDetails(int 456) | Views/Home/FilmDetails |
Secondly, the Action uses the Find() method to extract a record based on the primary key.
The Find() method uses the primary key to find an entity and return it. A null value is returned if no entity found or the entity is not in context
The previoulsy used FirstOrDefault() and ToList() methods, are methods of the DbContext. However, Find() differs in that it is a method of DbSet class.
Create a view at Views/Home/FilmDetails.cshtml which will receive the model.
This is exactly the same as the previous example, in that the Model is available to the view and so dot syntax can be used to extract values such as FilmTitle above.
To test the file call a page using a URL that includes a valid primary key from the database ie localhost:5001/Home/FilmDetails/1.
Amend the Views/Home/AllFilms View to link to the FilmDetails passing the id of the film.
This is done by using the Tag Helper asp-controller, asp-action and asp-route-id
Save and test via the AllFilms to link to the FilmDetails.
Notice the URL appears as localhost:5001/Home/FilmDetails/2