...

/

Manipulating Data Using Razor Pages

Manipulating Data Using Razor Pages

Learn about enabling model functionality in ASP.NET Core using Razor Pages, including modifying models, defining forms, and injecting dependency services into Razor Pages.

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:

Press + to interact
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:

Press + to interact
[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 is decorated with the [BindProperty] attribute so that we can easily connect HTML elements on the web page to properties in the Supplier class.

  • We added a method ...