ASP.NET Core: Razor Pages

Adding Data

Setting Up a New View and Model

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

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

Amending the Model File to Use the Entity Framework

Add a new private readonly variable for the database context.

Pages/Films/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.

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

Pages/Films/AddFilm.cshtml.cs

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

Pages/Films/AddFilm.cshtml.cs

Building the HTML form in the View

Now the model is aware of the MyNewFilm database context we can create a HTML form using tag-helpers.

Pages/Films/AddFilm.cshtml

Adding the Data to Database

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

Pages/Films/AddFilm.cshtml.cs

The above uses the AddAsync() method of Entity Framework to add the data. This is an asynchronous method as such the OnPost() handler is set to async Task

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

Server Side Validation

As FilmTitle was Required field in the original Model then server side validation is automatically added.

To provide feedback in the View add:

Pages/Films/AddFilm.cshtml