Razor Pages (an alternative to MVC)

Menu
Menu

Databases and Razor: Extract One Record by ID

Setting Up a Page and PageModel

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.

Add a new private readonly variable for the database context.

PAGEMODEL: Pages/Films/DetailPage.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/DetailPage.cshtml.cs

Create a variable named FilmById to hold the film details for the Id we pass to this file.

PAGEMODEL: Pages/DetailPage.cshtml.cs

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

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

Amend the onGet() handler to receive an Id as a parameter and then to use this as the value in the Find() method.

PAGEMODEL: Pages/DetailPage.cshtml.cs

Amending the Page File to Display the Data

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

PAGE: Pages/DetailPage.cshtml

Amending the AllFilms File to Pass the Id

Amend the AllFilms Page to link to the DetailPage passing the Id of the record.

This is done by using the tag-helper asp-page and asp-route-id

PAGE: Pages/AllFilms.cshtml

Save and test via the AllFilms to link to the DetailPage.

Notice the URL appears as:

This is the querystring that pass the value to from AllFilms to the DetailPage page. It is neater to hide the querystring to create a more user friendly URL.

Amend the DetailPage page's @pagedirective which appears at the very top of the page. Amend it to include a route parameter in this example an int named Id.

PAGE: Pages/DetailPage.cshtml

Test from the AllFilms and inspect the link. It should now appears as: