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:
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:
[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 theSupplier
class.We added a method ...