Razor Pages (an alternative to MVC)

Menu
Menu

Adding a New Record

Setting Up a Page and PageModel

Create a new Page called AddFilm.cshtml as done in the previous examples to create a Page and PageModel.

Edit the PageModel to Use the Entity Framework

Add a new private readonly variable to the PageModel AddFilm.cshtml.cs to reference the database context.

Pages/AddFilm.cshtml.cs.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.

Pages/AddFilm.cshtml.cs

Create a variable of type Film named MyNewFilm to hold the data for the new film.

Pages/AddFilm.cshtml.cs

Building the HTML form in the Page

Now the PageModel is aware of the database context we can edit the Page to add a HTML form using Tag Helpers.

PAGE: Pages/AddFilm.cshtml

Adding the Data to Database

Back in the PageModel AddFilm.cshtml.cs add a OnPost() handler to receive the data from the form of method post.

PAGEMODEL: Pages/AddFilm.cshtml.cs

The above uses the Add() method of DbContext as would be done with the MVC approach.

The return statements send the user back to the AllFilms page or reload the page so that validation errors can be displayed to the user.