Model binding in Razor pages Using Database
Create a New Asp.net Core Web App
Project is created with following structure
Lets Add funcationality for Products in Ecommerces Portal
Step 1: Add a Data Model
In Solution Explorer, Right click on the project, Add > New Folder. Name the folder Models.
Right-click the Models folder. Select Add > Class. Name the class Product.
Step 2: Scaffold the product model
1. Right-click on the Pages folder > Add > New Folder.
2. Name the folder Products.
3. Right-click on the Pages/Products folder > Add > New Scaffolded Item.
4. In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.
Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
In the Model class drop down, select Product
In the Data context class row, select the + (plus) sign.
A. In the Add Data Context dialog, the class is generated rename it as ProductsContext.
B. Select Add.
The scaffold process The scaffold process did following: -
Add all required packages, Update all dependencies, and generate Scaffold necessary code
creates the following folders and files:
A. Pages/Products: Create, Delete, Details, Edit, and Index.
C. Adds the following highlighted code to the Program.cs file:
Step 3: Change connection string appsettings.development.json file
Step 4: Create the initial database schema using EF's migration feature
The migrations feature in Entity Framework Core provides a way to:
- Create the initial database schema.
- Incrementally update the database schema to keep it in sync with the app's data model. Existing data in the database is preserved.
Open Package Manager Console
Tools menu, select NuGet Package Manager > Package Manager Console
In the PMC, enter the following commands:
- The Add-Migration command generates code to create the initial database schema. The schema is based on the model specified in DbContext. The InitialCreate argument is used to name the migration.
- The Update-Database command runs the Up method in migrations that have not been applied. In this case, the command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.
Test the app
Run the app and append /Products and enter (http://localhost:port/products)
Test the Create New link.
Test the Edit, Details, and Delete links.
Razor Pages are derived from PageModel. By convention, the PageModel derived class is named PageNameModel
When the return type is IActionResult or Task<IActionResult>, a return statement must be provided.
The @page directive
The @page Razor directive makes the file an MVC action, which means that it can handle requests. @page must be the first Razor directive on a page.
The @model directive
The @model directive specifies the type of the model passed to the Razor Page.
The ProductsContext object handles the task of connecting to the database and mapping Product objects to database records.