CRUD Operation With Razor Pages In ASP.NET Core 2.0

ASP.NET Core

In this article, we are going to learn how to perform CRUD operations with Razor Pages in ASP.NET CORE 2.0. Before getting started let’s get a basic idea of what Razor pages are.

What are Razor pages?

Razor Pages is a new feature of ASP.NET Core MVC that makes coding page-focused scenarios easier and more productive.

Definition taken from here.

Where do we use Razor pages?

There are some pages in the application which are not too big where you are still required to create a controller and add action Method, along with that we need to add View.

In this part we can use Razor Pages which has code behind it . We just need to add a Razor Page and on view “Customer.cshtml” you can design your view and on the same page you can write code for handling requests such as get and Post, but if you think you want to separate it then you can use code behind  “Customer.cshtml.cs”

ASP.NET Core

Pre prerequisite for Razor Pages Application

  1. Install .Net Core 2.0 SDK
    URL - https://www.microsoft.com/net/download/core

    ASP.NET Core

    ASP.NET Core
  1. Install Visual Studio 2017 version 15.3 or later
    URL - https://www.visualstudio.com/downloads/

Visual Studio Community 2017

Free, fully-featured IDE for students, open-source and individual developers 

Let’s start with the Create Razor Pages application.

ASP.NET Core

Creating Razor page project

For creating a project just choose File Menu from Visual studio IDE then New, inside that, choose Project.

ASP.NET Core

After choosing a project, a new dialog will pop up with the name “New Project”. In that, we are going to choose Visual C# Project Templates - Web - ASP.NET Core Web Application. Then, we are going to name the project as “RazorPagesDemo”.

ASP.NET Core

After naming the project we are going click on OK button to create a project.

 A new dialog will pop up for choosing templates for Creating “ASP.NET Core Web Application” in that template we are going to Create ASP.Net Core Razor Pages application. That's why we are going to choose “Web Application” and next we will have the option to choose framework 1.Net core or 2.Net Framework, and also ASP.NET Core Version. In that, we are going to choose “.Net Core” and “ASP.NET Core 2.0” as ASP.NET Core Version as click on OK button to create a project.

ASP.NET Core

After clicking on OK button it will start to create a project.

ASP.NET Core

Project Structure

You'll see some new project structure you in this project. There are no Model, View, Controller folders in this project.

You will only able to see Pages folder in this folder all Razor pages are stored.

ASP.NET Core

One thing which is back again is a  little code behind to make thinks little easier.
ASP.NET Core

Yes Razor pages has Code behind.

ASP.NET Core

In the first steps we are going to add a model folder and inside that folder we are going to add Customer Model.

Creating Model folder and Adding Customer Model in it

In this part, we are going to add a Model folder in “RazorPagesDemo” Project after adding folder next we are going to add Customer class (Model) in Models folder.

For details see below snapshot,

ASP.NET Core

After adding Customer Model now next we are going to add a property to this class.

Adding Properties and DataAnnotations to Customer Model

In Razor pages, you can use the same DataAnnotations which are there in MVC. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace RazorPagesDemo.Models  
  9. {  
  10.     [Table("CustomerTB")]  
  11.     public class Customer  
  12.     {  
  13.         [Key]  
  14.         public int CustomerID { get; set; }  
  15.         [Required(ErrorMessage = "Enter Name")]  
  16.         public string Name { get; set; }  
  17.         [Required(ErrorMessage = "Enter Address")]  
  18.         public string Address { get; set; }  
  19.         [Required(ErrorMessage = "Enter Country Name")]  
  20.         public string Country { get; set; }  
  21.         [Required(ErrorMessage = "Enter City Name")]  
  22.         public string City { get; set; }  
  23.         [Required(ErrorMessage = "Enter City Phoneno")]  
  24.         public string Phoneno { get; set; }  
  25.     }  
  26. }  

After completing with adding model and DataAnnotations next we are going to add Razor page.

Adding Razor Page to project

For adding Razor page just right click on Pages folder then select Add - inside that select New Item.

ASP.NET Core

After selecting New Item a new dialog will pop up with name “New item” in that we are going to select Razor Page Item and name it as “Customer.cshtml” and click on add button.

ASP.NET Core

After clicking on add button below is Pages folder structure in this part you can see “Customer.cshtml” View with “Customer.cshtml.cs” code behind which will have all handlers’ part to handle the request.

ASP.NET Core

Understanding “Customer.cshtml” View

This “Customer.cshtml” file looks more like a Razor View.

In Customer.cshtml view the first thing you are going to see is @page directive which tells Razor view engine that this page is Razor page, not MVC View and it makes a page to handle request directly without going to the controller.

ASP.NET Core

Next, you can see @model is a CustomerModel is a code-behind class name.

ASP.NET Core

The CustomModel file name is the same name as Razor page file “Customer.cshtml.cs” just “.cs” appended at last.

This CustomModel class inherits from PageModel which make this class to handle the request.

Next thing you can see in CustomModel is OnGet Method (handler) which handles get request.

Let’s start will simple example then we are going to start with CRUD operation.

Displaying Message

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.AspNetCore.Mvc.RazorPages;  
  7.   
  8. namespace RazorPagesDemo.Pages  
  9. {  
  10.     public class CustomerModel : PageModel  
  11.     {  
  12.         public string WelcomeMessage { get; set; }  
  13.   
  14.         public void OnGet()  
  15.         {  
  16.             WelcomeMessage = "WelCome to Razor Pages by Saineshwar Bageri";  
  17.         }  
  18.     }  
  19. }  

In this part, we have simply added a string with name WelcomeMessage and assigned value to it.

Next, on view, we are going to display a message in the following format.

ASP.NET Core

Now Save Application and run.

And to access page just enter Page Name “Customer”.

URL - http://localhost:######/Customer 

E.g. ####### (port number)

Wow, we have created  our first razor page.

ASP.NET Core

CRUD Operation with Razor Pages

The first thing we are going to do is Create Customer; for doing that we have added Customer Model in the Models folder.

Next, we are going to declare that model in CustomerModel class as below.

Code snippet of CustomerModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.AspNetCore.Mvc.RazorPages;  
  7. using RazorPagesDemo.Models;  
  8.   
  9. namespace RazorPagesDemo.Pages  
  10. {  
  11.     public class CustomerModel : PageModel  
  12.     {  
  13.           
  14.         public Customer Customer { get; set; }  
  15.   
  16.         public void OnGet()  
  17.         {  
  18.              
  19.         }  
  20.     }  
  21. }  

After declaring this Customer model in CustomerModel class now Customer Model is accessible on Razor page file (Customer.cshtml)

Now let’s Design View.

Adding input Controls on Customer.cshtml View

In this part, we have used New MVC tag helper to create input fields and we have added all model properties on View.

Note

if you want to learn about details of New Tag Helpers visit this link.

https://blogs.msdn.microsoft.com/cdndevs/2015/08/06/a-complete-guide-to-the-mvc-6-tag-helpers/

  1. @page  
  2. @using RazorPagesDemo.Models @*namespace*@  
  3. @model CustomerModel  
  4. <script src="~/lib/jquery/dist/jquery.js"></script>  
  5. <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>  
  6. <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>  
  7.   
  8.   
  9. <div class="container">  
  10.     <h3>Add Customer</h3>  
  11.     <hr />  
  12.     <br />  
  13.     <form method="post">  
  14.         <div class="row">  
  15.             <div class="col-md-4">  
  16.                 <label asp-for="Customer.Name"></label>  
  17.                 <input asp-for="Customer.Name" class="form-control" />  
  18.                 <span class="alert-danger" asp-validation-for="Customer.Name"></span>  
  19.             </div>  
  20.         </div>  
  21.         <div class="row">  
  22.             <div class="col-md-4">  
  23.                 <label asp-for="Customer.Address"></label>  
  24.                 <input asp-for="Customer.Address" class="form-control" />  
  25.                 <span class="alert-danger" asp-validation-for="Customer.Address"></span>  
  26.             </div>  
  27.         </div>  
  28.         <div class="row">  
  29.             <div class="col-md-4">  
  30.                 <label asp-for="Customer.Country"></label>  
  31.                 <input asp-for="Customer.Country" class="form-control" />  
  32.                 <span class="alert-danger" asp-validation-for="Customer.Country"></span>  
  33.             </div>  
  34.         </div>  
  35.   
  36.         <div class="row">  
  37.             <div class="col-md-4">  
  38.                 <label asp-for="Customer.City"></label>  
  39.                 <input asp-for="Customer.City" cl class="form-control" />  
  40.                 <span class="alert-danger" asp-validation-for="Customer.City"></span>  
  41.             </div>  
  42.         </div>  
  43.   
  44.         <div class="row">  
  45.             <div class="col-md-4">  
  46.                 <label asp-for="Customer.Phoneno"></label>  
  47.                 <input asp-for="Customer.Phoneno" class="form-control" />  
  48.                 <span class="alert-danger" asp-validation-for="Customer.Phoneno"></span>  
  49.             </div>  
  50.         </div>  
  51.         <br />  
  52.         <input type="submit" value="Save" class="btn btn-primary" />  
  53.         <a class="btn btn-default" href="/allcustomer">Cancel</a>  
  54.     </form>  
  55. </div>  

Now save Application and run project.

And to access page just enter Page Name “Customer”.

URL - http://localhost:######/Customer 

Eg. ####### (port number)

Snapshot of Customer page

ASP.NET Core

After entering URL the first request goes to OnGet handler.

While Debugging

ASP.NET Core

Note - Handlers

There are 2 default handlers in Razor pages

  1. OnGet()
  2. OnPost()

If you want you can create your own handlers you can create I will show in the upcoming example.

After completing with Designing Razor Page file (“Customer.cshtml”) now let’s add another handler to handle post request.

Adding OnPost Handler

In this part, we are going to add Post Handler to get all data which is filled by the user.

ASP.NET Core

We have added OnPost handler but it is not filling data of model what we have posted.

While Debugging

ASP.NET Core

For binding data, we need to add [BindProperty] attribute on the (Customer) property we declare in CustomerModel class.

ASP.NET Core

If we try to Post model again then we are going to get model populated with values. Let’s save these values in the database.

Database Part

I have created a database with the name “CustomerDB” and in that, it has “CustomerTB” table.

ASP.NET Core

First thing for saving data in Database we need an ORM we are going to use “Entity framework core”

Installing package for Entity framework core from NuGet

To install the package, just right click on the project (RazorPagesDemo) and then select Manage NuGet package. The below dialog of NuGet Package Manager will pop up.

In the browse tab, type “Microsoft.EntityFrameworkCore.SqlServer” in the search box and just click on Install button.

 Microsoft.EntityFrameworkCore.SqlServer

ASP.NET Core

Adding Connection string and Setting up DbContext

After adding a reference, now add a connection string in appsetting.json file.

ASP.NET Core

Now, let’s add a class with the name DatabaseContext in Models folder.

For adding a model, just right click on Models folder. Then, select Add - Class. An "Add New Item" dialog will pop up with default class selected. Name the class as DatabaseContext and click on Add button

ASP.NET Core

After adding a DatabaseContext class, next, we are going to inherit DbContext class.

After inheriting with DbContext, next we are creating a constructor which takes DbContextOptions as an input parameter and also inherits the base class constructor (: base(options)) [DbContext].

Code snippet of DatabaseContext class

  1. using Microsoft.EntityFrameworkCore;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace RazorPagesDemo.Models  
  8. {  
  9.     public class DatabaseContext : DbContext  
  10.     {  
  11.         public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)  
  12.         {  
  13.   
  14.         }  
  15.     }  
  16. }  

Next, we are going to add a new Service in Startup.cs class for injecting dependency.

Now, whenever you use DatabaseContext class, DbContext instance will be injected there.

ASP.NET Core

After adding CustomerTB Model, in our next step, we are going to add DbSet of all models in DatabaseContext class.

Adding DbSet for CustomerTB Model in DatabaseContext class

Now, let's add DbSet for CustomerTB Model in DatabaseContext class, as shown below.

ASP.NET Core

After adding DbSet in DatabaseContext class next we are going to add a constructor in CustomerModel class.

Setting up Dependency injection at CustomerModel class

In this part wherever we use DatabaseContext class, DbContext instance will be injected there.

ASP.NET Core

Now using (“_Context”) object we can save data in the database, let’s make a change in OnPost handler to save data in the database.

Below snapshot, you can see we have made changes in OnPost handler

ASP.NET Core

Code snippet of CustomerModel class

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesDemo.Models;  
  4.   
  5. namespace RazorPagesDemo.Pages  
  6. {  
  7.     public class CustomerModel : PageModel  
  8.     {  
  9.         DatabaseContext _Context;  
  10.         public CustomerModel(DatabaseContext databasecontext)  
  11.         {  
  12.             _Context = databasecontext;  
  13.         }  
  14.   
  15.         [BindProperty]  
  16.         public Customer Customer { get; set; }  
  17.   
  18.         public void OnGet()  
  19.         {  
  20.   
  21.         }  
  22.   
  23.         public ActionResult OnPost()  
  24.         {  
  25.             var customer = Customer;  
  26.             if (!ModelState.IsValid)  
  27.             {  
  28.                 return Page(); // return page  
  29.             }  
  30.   
  31.             customer.CustomerID = 0;  
  32.             var result = _Context.Add(customer);  
  33.             _Context.SaveChanges(); // Saving Data in database  
  34.   
  35.             return RedirectToPage("AllCustomer");  
  36.         }  
  37.     }  
  38. }  

Now save Application and run project.

And to access page just enter Page Name “Customer”.

URL - http://localhost:######/Customer  Eg. ####### (port number)

Now on save button data will be saved in the database.

ASP.NET Core

Database Output

ASP.NET Core

Now we have completed adding part let’s add another Razor Page to display all customers (AllCustomer).

Adding All Customer Razor page

In this part, we are going to add another razor page to display All Customer which is saved in the database.

Adding new razor page in same way as we added customer Razor page

ASP.NET Core

After adding AllCustomer.cshtml Razor page next we are going to adding Constructor and OnGet Handler

Adding Constructor and OnGet Handler

In this part onGet Handler we are going to get all customer details from the database and assign those values to CustomerList and this CustomerList on razor page we are going to iterate and display customer details.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesDemo.Models;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6.   
  7. namespace RazorPagesDemo.Pages  
  8. {  
  9.     public class AllCustomerModel : PageModel  
  10.     {  
  11.         DatabaseContext _Context;  
  12.         public AllCustomerModel(DatabaseContext databasecontext)  
  13.         {  
  14.             _Context = databasecontext;  
  15.         }  
  16.   
  17.         public List<Customer> CustomerList { get; set; }  
  18.   
  19.         public void OnGet()  
  20.         {  
  21.             var data = (from customerlist in _Context.CustomerTB  
  22.                         select customerlist).ToList();  
  23.   
  24.             CustomerList = data;  
  25.         }  
  26.     }  
  27. }  

Adding AllCustomer.cshtml

On AllCustomer razor page view we are going to declare @page directive after that namespace and at last

@model which is “AllCustomerModel

ASP.NET Core

Now we are going to Iterate data (CustomerList).

Code snippet of AllCustomerModel.cshtml

  1. @page  
  2. @using RazorPagesDemo.Models  
  3. @model AllCustomerModel  
  4.   
  5. <h2>Index</h2>  
  6.   
  7. <p>  
  8.     <a asp-page="Customer">Create New Customer</a>  
  9. </p>  
  10. <table class="table">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>  
  14.                 @Html.DisplayName("Name")  
  15.             </th>  
  16.             <th>  
  17.                 @Html.DisplayName("Address")  
  18.             </th>  
  19.             <th>  
  20.                 @Html.DisplayName("Country")  
  21.             </th>  
  22.             <th>  
  23.                 @Html.DisplayName("City")  
  24.             </th>  
  25.             <th>  
  26.                 @Html.DisplayName("Phoneno")  
  27.             </th>  
  28.             <th>Edit | Delete</th>  
  29.         </tr>  
  30.     </thead>  
  31.     <tbody>  
  32.         @foreach (var item in Model.CustomerList)  
  33.         {  
  34.             <tr>  
  35.                 <td>  
  36.                     @Html.DisplayFor(modelItem => item.Name)  
  37.                 </td>  
  38.                 <td>  
  39.                     @Html.DisplayFor(modelItem => item.Address)  
  40.                 </td>  
  41.                 <td>  
  42.                     @Html.DisplayFor(modelItem => item.Country)  
  43.                 </td>  
  44.                 <td>  
  45.                     @Html.DisplayFor(modelItem => item.City)  
  46.                 </td>  
  47.                 <td>  
  48.                     @Html.DisplayFor(modelItem => item.Phoneno)  
  49.                 </td>  
  50.                 <td>  
  51.                     <a asp-page="./EditCustomer" asp-route-id="@item.CustomerID">Edit</a> |  
  52.                     <a asp-page="./AllCustomer" onclick="return confirm('Are you sure you want to delete this item?');" asp-page-handler="Delete" asp-route-id="@item.CustomerID">Delete</a>  
  53.                 </td>  
  54.             </tr>  
  55.         }  
  56.     </tbody>  
  57. </table> 

While iterating CustomerList you might have seen a new tag helper which we have used for Creating link for Edit and Delete button.

Edit link

In edit link, we have just assign EditCustomer razor page name to “asp-page” property and “asp-route-id” we have assigned CustomerID to it, We haven't added EditCustomer razor page yet but we will soon.

  1. <a asp-page="./EditCustomer" asp-route-id="@item.CustomerID">Edit</a>  

Delete link

In Delete link we have just assigned AllCustomer razor page names to “asp-page” property and  we have assigned CustomerID to “asp-route-id; " next we are going to assign “asp-page-handler” property which is a new one especially for Razor pages. Here we are going to add Handler name “Delete” which we are going to create in AllCustomer Razor page.

  1. <a asp-page="./AllCustomer" onclick="return confirm('Are you sure you want to delete this item?');"   
  2. asp-page-handler="Delete" asp-route-id="@item.CustomerID">Delete</a>  

Adding Delete Handler

In Razor pages, we have 2 default handlers, OnGet and OnPost but we can add custom handlers also to handle OnGet and OnPost request

Below is a snapshot of it.

ASP.NET Core

Code snippet of Delete Handler

In this part, we are going add Delete handler “OnGetDelete” which take CustomerID as input.

After receiving CustomerID (id) next we are going get Customer details from the database by passing CustomerID (id) and pass it to remove method to delete it and finally we redirect after deleting to the All Customer page.

  1. public ActionResult OnGetDelete(int? id)  
  2.         {  
  3.             if (id != null)  
  4.             {  
  5.                 var data = (from customer in _Context.CustomerTB  
  6.                             where customer.CustomerID == id  
  7.                             select customer).SingleOrDefault();  
  8.   
  9.                 _Context.Remove(data);  
  10.                 _Context.SaveChanges();  
  11.             }  
  12.             return RedirectToPage("AllCustomer");  
  13.         }  

Now save the application and run it.

Access AllCustomer page.

ASP.NET Core

Now if you see delete link by hovering it you can see we are passing id (CustomerId) and along with that we are also passing handler name (“Delete”)

e.g. http://localhost:49989/AllCustomer?id=2&handler=Delete

While debugging

ASP.NET Core

Finally, we have created delete handler the last thing  that remains in CRUD operation is Edit Customer (Update) let’s start adding EditCustomer Razor page.

Adding EditCustomer page

In this part, we are going to add another Razor page to Edit Customer Details which is saved in the database.

Adding new Razor page in the same way as we add customer razor page

ASP.NET Core

After adding EditCustomer.cshtml Razor page next we are going to adding Constructor and OnGet Handler

Adding Constructor and OnGet Handler

In this part onGet Handler, we are going to get CustomerID (id) from query string from that we are going to get Customer Details from the database and assign those values to Customer Model this model we are going to send to Edit Customer View.

Code snippet of Edit Customer Model

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.AspNetCore.Mvc.RazorPages;  
  7. using RazorPagesDemo.Models;  
  8.   
  9. namespace RazorPagesDemo.Pages  
  10. {  
  11.     public class EditCustomerModel : PageModel  
  12.     {  
  13.         DatabaseContext _Context;  
  14.         public EditCustomerModel(DatabaseContext databasecontext)  
  15.         {  
  16.             _Context = databasecontext;  
  17.         }  
  18.   
  19.   
  20.         [BindProperty]  
  21.         public Customer Customer { get; set; }  
  22.   
  23.         public void OnGet(int? id)  
  24.         {  
  25.             if (id != null)  
  26.             {  
  27.                 var data = (from customer in _Context.CustomerTB  
  28.                             where customer.CustomerID == id  
  29.                             select customer).SingleOrDefault();  
  30.   
  31.                 Customer = data;  
  32.             }  
  33.         }  
  34.     }  
  35. }  

Next, we are going to design Edit View for displaying records for editing.

Code snippet of Edit Customer Page

In this page we are creating edit page means we are going to show record and allow the user to edit details and update it.

The first thing you are going to see is @page"{id: int}" directive, which tells that page need "{id: int}"int id  (CustomerID) then only it will accept requests else it will returns an HTTP 404 (not found) error.

It id (CustomerID) we are going to send from All Customer View Edit link.

Note

@page"{id: int}" it is kind of routing in Razor pages.

Link example: - http://localhost:49989/EditCustomer/1

  1. @page "{id:int}"  
  2. @using RazorPagesDemo.Models  
  3. @model EditCustomerModel  
  4.   
  5. <div class="container">  
  6.     <h3>Edit Customer</h3>  
  7.     <hr />  
  8.     <br />  
  9.     <form method="post">  
  10.         <input asp-for="Customer.CustomerID" type="hidden" />  
  11.         <div class="row">  
  12.             <div class="col-md-4">  
  13.                 <label asp-for="Customer.Name"></label>  
  14.                 <input asp-for="Customer.Name" class="form-control" />  
  15.             </div>  
  16.         </div>  
  17.         <div class="row">  
  18.             <div class="col-md-4">  
  19.                 <label asp-for="Customer.Address"></label>  
  20.                 <input asp-for="Customer.Address" class="form-control" />  
  21.             </div>  
  22.         </div>  
  23.         <div class="row">  
  24.             <div class="col-md-4">  
  25.                 <label asp-for="Customer.Country"></label>  
  26.                 <input asp-for="Customer.Country" class="form-control" />  
  27.             </div>  
  28.         </div>  
  29.   
  30.         <div class="row">  
  31.             <div class="col-md-4">  
  32.                 <label asp-for="Customer.City"></label>  
  33.                 <input asp-for="Customer.City" cl class="form-control" />  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="row">  
  38.             <div class="col-md-4">  
  39.                 <label asp-for="Customer.Phoneno"></label>  
  40.                 <input asp-for="Customer.Phoneno" class="form-control" />  
  41.             </div>  
  42.         </div>  
  43.         <br />  
  44.         <input type="submit" value="Save" class="btn btn-primary" />  
  45.         <a class="btn btn-default" href="/allcustomer">Cancel</a>  
  46.     </form>  
  47. </div>  

Now save the application and run.

Access All Customer page

ASP.NET Core

Now hover edit link you can see URL which is generated (http://localhost:49989/EditCustomer/1) now click on Edit link it will display EditCustomer Page.

While debugging

ASP.NET Core

ASP.NET Core

Now we have completed Edit page OnGet Handler implementation which helps to display customer data in edit mode, next we need to update data; for doing that we need to Add Onpost Handler which will handle post request.

Code snippet of OnPost Request

In this part we are posting data which will update Customer model which we are going to check it is valid or not if it is not valid then we are going to return Page() which will show Error Message.

If it is valid then we are going to update data in the database and redirect page to AllCustomer Page.

Code snippet of Complete EditCustomerModel

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesDemo.Models;  
  4. using System.Linq;  
  5.   
  6. namespace RazorPagesDemo.Pages  
  7. {  
  8.     public class EditCustomerModel : PageModel  
  9.     {  
  10.         DatabaseContext _Context;  
  11.         public EditCustomerModel(DatabaseContext databasecontext)  
  12.         {  
  13.             _Context = databasecontext;  
  14.         }  
  15.   
  16.   
  17.         [BindProperty]  
  18.         public Customer Customer { get; set; }  
  19.   
  20.         public void OnGet(int? id)  
  21.         {  
  22.             if (id != null)  
  23.             {  
  24.                 var data = (from customer in _Context.CustomerTB  
  25.                             where customer.CustomerID == id  
  26.                             select customer).SingleOrDefault();  
  27.   
  28.                 Customer = data;  
  29.             }  
  30.         }  
  31.   
  32.   
  33.         public ActionResult OnPost()  
  34.         {  
  35.             var customer = Customer;  
  36.             if (!ModelState.IsValid)  
  37.             {  
  38.                 return Page();  
  39.             }  
  40.   
  41.             _Context.Entry(customer).Property(x => x.Name).IsModified = true;  
  42.             _Context.Entry(customer).Property(x => x.Phoneno).IsModified = true;  
  43.             _Context.Entry(customer).Property(x => x.Address).IsModified = true;  
  44.             _Context.Entry(customer).Property(x => x.City).IsModified = true;  
  45.             _Context.Entry(customer).Property(x => x.Country).IsModified = true;  
  46.             _Context.SaveChanges();  
  47.             return RedirectToPage("AllCustomer");  
  48.         }  
  49.     }  
  50. }   

Snapshot of Edit Customer Page

ASP.NET Core

We have updated Name of Customer. Now let’s view All customer view  -- that value is updated.

ASP.NET Core

Wow, we have successfully Updated Customer Name in the database.

While debugging

ASP.NET Core

Validation of Form

In Razor page validation is similar to MVC validation and  there is no change in it. Just add DataAnnotations attribute on Model properties and on view starts its validation control.

ASP.NET Core 
ASP.NET Core

Finally, we have learned, about Razor Pages and along with that how to do CRUD operations with Razor Pages in a step by step way. I hope you liked my article.