Search⌘ K
AI Features

Manipulating Data Using Razor Pages

Explore how to add and manage data in ASP.NET Core Razor Pages by creating forms that bind to model properties, handling HTTP POST requests for inserting suppliers, and injecting services for data retrieval. Learn to build interactive web pages that perform CRUD operations using Entity Framework Core and Razor Pages syntax.

We will now add functionality to insert a new supplier

Enabling a model to insert entities

First, we will modify the supplier model so that it responds to HTTP POST requests when a visitor submits a form to insert a new supplier:

Step 1: In the Northwind.Web project, in the Pages folder, open Suppliers.cshtml.cs and import the following namespace:

C#
using Microsoft.AspNetCore.Mvc; // [BindProperty], IActionResult

Step 2: In the SuppliersModel class, add a property to store a single supplier, and a method named OnPost that adds the supplier to the Suppliers table in the Northwind database if its model is valid, as shown in the following code:

C#
[BindProperty]
public Supplier? Supplier { get; set; }
public IActionResult OnPost()
{
if ((Supplier is not null) && ModelState.IsValid)
{
db.Suppliers.Add(Supplier);
db.SaveChanges();
return RedirectToPage("/suppliers");
}
else
{
return Page(); // return to original page
}
}

While reviewing the preceding code, note the following:

  • We added a property named Supplier that ...