MVC: Extracting One Record

Extracting One Record

Amending the Controller to Retrieve the Data

In the previous example (Extracting all records) the DbContext had already been made availble to the 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.

Set up an Action

Add a Task/Action to the controller called OneFilm. The URL called to see this will be localhost:5000/Home/OneFilm

CONTROLLER: Controllers/HomeController.cs

The Action stores Film data into a variable called model. This is done using the DbContext and its access to the Films data, on which the FirstOrDefault() method is called.

Note: The FirstOrDefault() method is a LINQ (Language Integrated Query) extension.

Create a View

Create a view at Views/Home/OneFilm.cshtml which will receive the model.

VIEW: Views/Home/OneFilm.cshtml

The Model is available to the view and so dot syntax can be used to extract values such as FilmTitle above. We can also use the Model to populate the ViewData["Title"] to give the page a unique title based on the film found.

Amemd the above sample to include other fields.