ASP.NET Core: Razor Pages

Extracting One Record

Setting Up a Page and Page Model

In the pages/Films folder, create a page called OneFilm.cshtml. Do so via:

This will create a .cshtml page and an associated .cshtml.cs page model file.

Amending the Page Model File to Retrieve the Data

Add a new private readonly variable for the database context.

PAGE MODEL: Pages/Films/OneFilm.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.

PAGE MODEL: Pages/Films/OneFilm.cshtml.cs

Create a variable named OneFilm to hold the just one film.

PAGE MODEL: Pages/Films/OneFilm.cshtml.cs

When using Entity Framework data can be retrieved with a range of methods, here we'll used FirstOrDefault

See how to do this asychronously ↗.

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

Amend the onGet() handler to populate the OneFilm variable with the first or default value in the data.

PAGE: Pages/Films/OneFilm.cshtml.cs

Amending the Page File to Display the Data

The above means the OneFilm data is available to the view to display via the Model. It doesn't have to be added to the ViewData property.

PAGE: Pages/Films/OneFilm.cshtml