Razor Pages (an alternative to MVC)

Menu
Menu

Databases and Razor: Extract All Records

Setting Up a Page and Page Model

In the pages create a new Razor Page called AllFilms.cshtml as previously described ensuring a PageModel is created as well.

This will create a .cshtml and associated PageModel .cshtml.cs file.

Amending the PageModel File to Retrieve the Data

Add a new private readonly variable for the database context.

PAGEMODEL: Pages/AllFilms.cshtml.cs

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.

Tip: Use the snippet ctor TAB TAB to build a constructor shell.

PAGEMODEL: Pages/AllFilms.cshtml.cs

Create a List property to hold the films extracted from the database called AllFilms.

PAGEMODEL: Pages/AllFilms.cshtml.cs

When using Entity Framework data can be retrieved with a range of techniques. Here we'll used ToList() method, which is a LINQ Extension Methods.

Tip: Use the CTRL . to add the required dependencies in this case EntityFrameWorkCore.

Amend the onGet() handler as follows:

PAGEMODEL: Pages/Films/AllFilms.cshtml.cs

The AllFilms list is now available to the page.

Amending the Page File to Display the Data

The above means the AllFilms data is available to the view to display. It doesn't have to be added to the ViewData property because of @model directive, so it can be accsssed directly as a variable with the @ symbol.

PAGE: Pages/Films/AllFilms.cshtml

The above uses a foreach to loop Films. Each FilmTitle is added to the page.

Challenge:

Amemd the above sample to include other fields.