ASP.NETCore Razor pages and ASP.NETCore MVC are both server rendered / server based frameworks for building web apps with .NET. In both techniques/approaches, we use Razor template engine to create UI/view components and processing logic that runs on the server and serves the html content back. Original razor page technique is/was developed to fit single page type apps which does not form a complex work-flow based web application. It more or less suits the traditional, simple web scripting where there is one html form component and a server- side processing component that accepts the submitted form, process data and sends the processed html back. The view page is coded as .cshtml page and the corresponding ‘Model’ page is coded as the .cs page. ASP.NET MVC on the other hand follows the full blown ‘Model – View – Controller’ pattern and structure. Choose between these two approaches based on the size, need, complexity of your application. Let us now see how we can develop a simple razor page web application to store a contact card without the need for a full blown MVC app.
Create new Razor Page Web app. project
First, create a new project in Visual Studio and select Razor Web app as shown below –
Name your web application, select the .NetCore version and click ‘Create’. Once you create the app. You should see below directory structure on the Solutions Explorer –
As with any ASP.NETCore web application, the program.cs includes the services and configurations to start and run the application. In addition to the normal stuff, it will also have the additional razor page service builder.Services.AddRazorPages(); and directive to map the razor pages – app.MapRazorPages();
Create Model class
Now, let us use code first approach to create the contact Model class and later create/scaffold the required razor pages, finally create the DB via Migrations to run the app.
Create new folder ‘Models’ under root project and add a new class – Contact.cs to hold the basic contact card data as follows –
Install Entity Framework Design for Migration and DB operation
Use below command under NPM console to install the required package –
PM > install-package Microsoft.EntityFrameworkCore.Design
Create Razor Pages
You may use scaffolding feature to create the razor pages as below –
Notice that the DB context class was automatically created by clicking the + button.
Razor pages will be created as below –
Use EF migration to add migration and finally update DB-
PM> add-migration “Init”
This will create the DB migrations scripts and will create the new DB with the configurations defined.
Run the Razor Page app.
Now its time to test your Razor Page app. Press Cntrl + F5 and you should see below app. running your CRUD pages for your contact card –