MVC: Extracting (All) Data

Extracting Data

Amending the Controller to Retrieve the Data

Amend the controller Controllers/HomeController.cs so that it extracts all the records from a table in the database. To do so the controller needs to be aware of the Dbcontext. Add a new private readonly variable for the database context.

CONTROLLER: Controllers/HomeController.cs

Now it is declared, the Dbcontext can be made available to the controller through dependency injection into the constructor.

CONTROLLER: Controllers/HomeController.cs

Set up an Action

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

CONTROLLER: Controllers/HomeController.cs

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

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

Create a View

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

VIEW: Views/Home/AllFilms.cshtml

The Model is available to the view and can be looped using a foreach. Each @item representss a Film object extracted into a List by the controller. As such dot syntax can be used to extract values such as FilmTitle above.

Amemd the above sample to include other fields.