CRUD Operations In ASP.NET Core 2 Razor Page With Dapper And Repository Pattern

This article will demonstrate how to perform CRUD operations in Razor Page which were introduced with Asp.Net Core 2 using Dapper and Repository Pattern.

To complete this demonstration in a simple manner, we will follow some steps as below.

Step 1

Create Razor Page in Asp.Net Core 2

Step 2

Create Database and Table

Step 3

Install Dapper

Step 4

Create Repository Class and Interface with Required Entity

Step 5

Create Connection String and get it on Repository Class

Step 6

Create Razor Page for CRUD Operations

Step 7

Implement Code in Razor Pages for performing CRUD Operations

Now we have defined six steps to complete this practical demonstration. So, let’s move to step by step and complete the task.

STEP 1: Create Razor Page in Asp.Net Core 2

To create Asp.Net Core 2 Razor Page project, open Visual Studio 2017 version 15.3 and above and make sure you have installed .Net Core SDK 2.0 with your system. If you don’t have this configuration with your system, please update your Visual Studio and system with these configurations.

I hope, you have installed latest version of Visual Studio with .Net Core SDK 2.0, so open Visual Studio and Go to File Menu > choose New > select Project. It will open “New Project” windows. From the New Project windows, you have to choose .Net Core from the left panel and then from the center panel choose “Asp.Net Core Web Application” and provide the suitable name like “RazorPagesExample” and click to OK.

Asp.Net Core

After clicking OK button, it will pop up with new window from there we can choose the template for Razor Page.

Asp.Net Core

From here, you have to choose “Web Application” to create Razor Page application and click to OK. It will take minutes or seconds to configure your project and finally we have project ready for demonstration.

STEP 2: Create Database and Table

Open SSMS [SQL Server Management Studio] and create new database name called it “TestDB” and inside that you have to create one table that is called “Product” using following SQL scripts. Now we have database and its corresponding table is ready.

  1. --Create Database  
  2. CREATE DATABASE TestDB  
  3. GO  
  4.   
  5. --Use Created Database  
  6. USE TestDB  
  7. GO  
  8.   
  9. --Create Table "Product"  
  10. CREATE TABLE Product(Id INT PRIMARY KEY IDENTITY(1,1), Name VARCHAR(25), Model VARCHAR(50), Price INT)  
  11.   
  12. --Insert dummy reocrd in table  
  13. INSERT INTO Product(Name, Model, Price) VALUES('Nokia 1''Nokia', 25000)  
  14.   
  15. SELECT * FROM Product  

STEP 3: Install Dapper

In one line, Dapper is micro ORM with high performance for SQL, MySQL etc.

It is simple step to install Dapper. Right click on the project and choose “Manage NuGet Packages”. It will open NuGet Package Manager from there you can search packages which need to be installed. So, now we will search “Dapper” and installed it. After installation, it will be shown inside the NuGet section which lies inside the “Dependencies” as follows in project.

Asp.Net Core

STEP 4: Create Repository Class and Interface with Required Entity

In this demonstration, we will perform CRUD operations for Product. How to see product data, how to add new product, how to edit existing product and how to delete existing product after confirmation, so here we should have an entity which is related to Product.

Create a new folder inside the project name called “Entity” and add a new class “Product.cs” as follows which should have product’s id, name, model and price. You can use Data Annotation here for validating the properties while adding or editing the data for the product

  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace RazorPagesExample.Entity  
  4. {  
  5.     public class Product  
  6.     {  
  7.         [Key]  
  8.         [Display(Name = "Product Id")]  
  9.         public int Id { get; set; }  
  10.   
  11.         [Required]  
  12.         [Display(Name="Product Name")]  
  13.         [StringLength(25, ErrorMessage ="Name should be 1 to 25 char in lenght")]  
  14.         public string Name { get; set; }  
  15.   
  16.         [Required]  
  17.         [Display(Name = "Model")]  
  18.         [StringLength(50, ErrorMessage = "Name should be 1 to 50 char in lenght")]  
  19.         public string Model { get; set; }  
  20.   
  21.         [Required]  
  22.         [Display(Name = "Price")]          
  23.         public int Price { get; set; }  
  24.     }  
  25. }  

Add one more folder and name called it “Repository” inside the main project folder and add one interface as “IProductRepository” which contains all required server side methods to perform CRUD operations

  1. using RazorPagesExample.Entity;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace RazorPagesExample.Repository  
  5. {  
  6.     public interface IProductRepository  
  7.     {  
  8.         int Add(Product product);  
  9.   
  10.         List<Product> GetList();  
  11.   
  12.         Product GetProduct(int id);  
  13.   
  14.         int EditProduct(Product product);  
  15.   
  16.         int DeleteProdcut(int id);  
  17.     }  
  18. }  

To implement the above interface “IProductRepository”, we have to create a repository class name called it “ProductRepository” as follows.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using RazorPagesExample.Entity;  
  6. using System.Data.SqlClient;  
  7. using Microsoft.Extensions.Configuration;  
  8. using Dapper;  
  9.   
  10. namespace RazorPagesExample.Repository  
  11. {  
  12.     public class ProductRepository : IProductRepository  
  13.     {  
  14.         IConfiguration _configuration;  
  15.   
  16.         public ProductRepository(IConfiguration configuration)  
  17.         {  
  18.             _configuration = configuration;  
  19.         }  
  20.   
  21.         public int Add(Product product)  
  22.         {  
  23.             var connectionString = this.GetConnection();  
  24.             int count = 0;  
  25.             using (var con = new SqlConnection(connectionString))  
  26.             {  
  27.                 try  
  28.                 {  
  29.                     con.Open();  
  30.                     var query = "INSERT INTO Product(Name, Model, Price) VALUES(@Name, @Model, @Price); SELECT CAST(SCOPE_IDENTITY() as INT);";  
  31.                     count = con.Execute(query, product);  
  32.                 }  
  33.                 catch (Exception ex)  
  34.                 {  
  35.                     throw ex;  
  36.                 }  
  37.                 finally  
  38.                 {  
  39.                     con.Close();  
  40.                 }  
  41.   
  42.                 return count;  
  43.             }  
  44.         }  
  45.   
  46.         public int DeleteProdcut(int id)  
  47.         {  
  48.             var connectionString = this.GetConnection();  
  49.             var count = 0;  
  50.   
  51.             using (var con = new SqlConnection(connectionString))  
  52.             {  
  53.                 try  
  54.                 {  
  55.                     con.Open();  
  56.                     var query = "DELETE FROM Product WHERE Id =" + id;  
  57.                     count = con.Execute(query);  
  58.                 }  
  59.                 catch (Exception ex)  
  60.                 {  
  61.                     throw ex;  
  62.                 }  
  63.                 finally  
  64.                 {  
  65.                     con.Close();  
  66.                 }  
  67.   
  68.                 return count;  
  69.             }  
  70.         }  
  71.   
  72.         public int EditProduct(Product product)  
  73.         {  
  74.             var connectionString = this.GetConnection();  
  75.             var count = 0;  
  76.   
  77.             using (var con = new SqlConnection(connectionString))  
  78.             {  
  79.                 try  
  80.                 {  
  81.                     con.Open();  
  82.                     var query = "UPDATE Product SET Name = @Name, Model = @Model, Price = @Price WHERE Id = @Id";  
  83.                     count = con.Execute(query, product);  
  84.                 }  
  85.                 catch (Exception ex)  
  86.                 {  
  87.                     throw ex;  
  88.                 }  
  89.                 finally  
  90.                 {  
  91.                     con.Close();  
  92.                 }  
  93.   
  94.                 return count;  
  95.             }  
  96.         }  
  97.   
  98.         public List<Product> GetList()  
  99.         {  
  100.             var connectionString = this.GetConnection();  
  101.             List<Product> products = new List<Product>();  
  102.   
  103.             using (var con = new SqlConnection(connectionString))  
  104.             {  
  105.                 try  
  106.                 {  
  107.                     con.Open();  
  108.                     var query = "SELECT * FROM Product";  
  109.                     products = con.Query<Product>(query).ToList();  
  110.                 }  
  111.                 catch (Exception ex)  
  112.                 {  
  113.                     throw ex;  
  114.                 }  
  115.                 finally  
  116.                 {  
  117.                     con.Close();  
  118.                 }  
  119.   
  120.                 return products;  
  121.             }  
  122.         }  
  123.   
  124.         public Product GetProduct(int id)  
  125.         {  
  126.             var connectionString = this.GetConnection();  
  127.             Product product = new Product();  
  128.   
  129.             using (var con = new SqlConnection(connectionString))  
  130.             {  
  131.                 try  
  132.                 {  
  133.                     con.Open();  
  134.                     var query = "SELECT * FROM Product WHERE Id =" + id;  
  135.                     product = con.Query<Product>(query).FirstOrDefault();  
  136.                 }  
  137.                 catch (Exception ex)  
  138.                 {  
  139.                     throw ex;  
  140.                 }  
  141.                 finally  
  142.                 {  
  143.                     con.Close();  
  144.                 }  
  145.   
  146.                 return product;  
  147.             }  
  148.         }  
  149.   
  150.         public string GetConnection()  
  151.         {  
  152.             var connection = _configuration.GetSection("ConnectionStrings").GetSection("ProductContext").Value;  
  153.             return connection;  
  154.         }  
  155.     }  
  156. }  

Above “ProductRepository” class has method available for CRUD operation like “Add”, “EditProduct”, “DeleteProudct”, “GetList” and “GetProduct”.

  • Add: It uses for adding new product into database.
  • EditProduct: It uses for editing existing product data.
  • DeleteProduct: This method uses for deleting existing product data after confirmation.
  • GetList: This gets all the available products data
  • GetProduct: It gets the data for single Product.

 These methods are internally making the call to database using Dapper.

STEP 5: Create Connection String and get it on Repository Class

Now we have to define our database connection string. As we know Asp.Net Core uses appsettings.json to define your app related to all configurations. So, we are going to add our connection string inside the appsettings.json file as follows

  1. {  
  2.   "Logging": {  
  3.     "IncludeScopes"false,  
  4.     "LogLevel": {  
  5.       "Default""Warning"  
  6.     }  
  7.   },  
  8.   "ConnectionStrings": {  
  9.     "ProductContext""Data Source=AAYUSH-PC; Database=TestDB; UID=sa; Password=*******;"  
  10.   }  
  11. }  

To get this connection string on Repository we have already made code with above repository using “GetConnection()” method that gives us “Connection String” as following code shown.

  1. public string GetConnection()  
  2.         {  
  3.             var connection = _configuration.GetSection("ConnectionStrings").GetSection("ProductContext").Value;  
  4.             return connection;  
  5.         }  

STEP 6: Create Razor Pages for CRUD Operations

Now it’s time to create Razor Pages for CRUD operations, so we will create three pages inside the Product folder as shown with below image.

Index.cshtml is responsible to show all product list with Edit and Delete buttons at the last column with corresponding data. Apart from that it will show one more button at the top of the table which uses to add new record as “Add New Product”.

Add.cshtml is responsible for adding new records along with validations if required data does not pass.

Edit.cshtml is responsible for editing the existing record with validations for required properties.

For deleting the data, it is already handled on Index.cshtml page using the corresponding “Delete” button, which deletes the record after user confirmation and refresh of  the page;

Asp.Net Core

STEP 7: Implement Code in Razor Pages for performing CRUD Operations

Before adding the actual code for the CRUD operations, you have to register your dependency class with Startup.cs as follows inside the ConfigurService method.

  1. public void ConfigureServices(IServiceCollection services)  
  2.         {              
  3.             services.AddMvc();  
  4.             services.AddSingleton<IConfiguration>(Configuration);  
  5.             services.AddTransient<IProductRepository, ProductRepository>();  
  6.         }  

Now the time has come to write actual CRUD operation code, so add the following code with corresponding files which will handle the CRUD operations.

Index.cshtml File

This file will contain the code to display the list of products with corresponding button to delete and edit the data as well as one button to add new record.

  1. @page  
  2. @model IndexModel  
  3. @{  
  4.     ViewData["Title"] = "Product page";  
  5. }  
  6. <script>  
  7.     function myFunction(x) {  
  8.         $("#item_view").modal();  
  9.     };  
  10.     $(document).ready(function () {  
  11.         $("#success-alert").hide();          
  12.         $("#success-alert").fadeTo(2000, 500).slideUp(500, function () {  
  13.             $("#success-alert").slideUp(500);  
  14.         });  
  15.     });  
  16.   
  17. </script>  
  18.   
  19. <div class="container">  
  20.     <div class="mail-box">  
  21.         <aside class="lg-side">  
  22.             <div class="inbox-head">  
  23.                 <h3>Razor Page CRUD Operation</h3>  
  24.             </div>  
  25.             <a class="btn btn-primary btn-sx pull-left" style="margin-top:20px;margin-bottom: 20px;" asp-page="/Product/Add">  
  26.                 <i class="glyphicon glyphicon-plus"></i> Add New Product  
  27.             </a>  
  28.             <br />  
  29.             @{  
  30.                 if (!string.IsNullOrEmpty(Model.Message))  
  31.                 {  
  32.                     <div class="alert alert-success" id="success-alert" style="margin-top: 40px;">  
  33.                         <button type="button" class="close" data-dismiss="alert">x</button>  
  34.                         <strong>@Model.Message ! </strong>  
  35.                     </div>  
  36.                 }  
  37.             }  
  38.   
  39.             <div class="inbox-body" style="margin-top:20px;">  
  40.                 <div class="mail-option">  
  41.   
  42.                     <table class="table table-inbox table-hover" style="border:2px solid black;">  
  43.                         <thead>  
  44.                             <tr class="unread">  
  45.                                 <th class="col-sm-2 view-message  dont-show">ID</th>  
  46.                                 <th class="view-message col-sm-3">NAME</th>  
  47.                                 <th class="col-sm-2">MODEL</th>  
  48.                                 <th class="view-message  text-left col-sm-2">PRICE</th>  
  49.                                 <th class="col-sm-1">OPERATION</th>  
  50.                             </tr>  
  51.                         </thead>  
  52.                         <tbody>  
  53.                             @foreach (var item in Model.productList)  
  54.                             {  
  55.                                 <tr>  
  56.                                     <td onclick="myFunction(this)" class="view-message  dont-show"><h5>@item.Id</h5></td>  
  57.                                     <td onclick="myFunction(this)" class="view-message"><h5>@item.Name</h5></td>  
  58.                                     <td onclick="myFunction(this)"><h4 style="margin-top: 5px;"><span class="label label-success ">@item.Model</span></h4></td>  
  59.                                     <td onclick="myFunction(this)" class="view-message  text-left"><h5>@item.Price</h5></td>  
  60.                                     <td>  
  61.                                         <form method="post">  
  62.                                             <span class="btn-group pull-right" style="margin-top: 5px">  
  63.                                                 <a class="btn btn-warning btn-xs" asp-page="/Product/Edit" asp-route-id="@item.Id" style="background-color: green; height: 29px; margin-top: -1px;">  
  64.                                                     <i class="glyphicon glyphicon-edit"></i>  
  65.                                                 </a>  
  66.   
  67.                                                 <button type="submit" class="btn btn-danger btn-xs" asp-page-handler="Delete" asp-route-id="@item.Id" style="height: 27px; margin-top: 0px;"  
  68.                                                         onclick="return confirm('Are you sure to delete this product?');">  
  69.                                                     <i class="glyphicon glyphicon-remove"></i>  
  70.                                                 </button>  
  71.   
  72.                                             </span>  
  73.                                         </form>  
  74.                                     </td>  
  75.                                 </tr>  
  76.                             }  
  77.                         </tbody>  
  78.                     </table>  
  79.                 </div>  
  80.             </div>  
  81.         </aside>  
  82.     </div>  
  83. </div>  

Index.cshtml.cs File

This is basically code-behind class for Index.cshtml file which contains the code for getting the data and deleting the selected records.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesExample.Repository;  
  4. using System.Collections.Generic;  
  5.   
  6.   
  7. namespace RazorPagesExample.Pages.Product  
  8. {  
  9.     public class IndexModel : PageModel  
  10.     {  
  11.         IProductRepository _productRepository;  
  12.         public IndexModel(IProductRepository productRepository)  
  13.         {  
  14.             _productRepository = productRepository;  
  15.         }  
  16.   
  17.         [BindProperty]  
  18.         public List<Entity.Product> productList { get; set; }  
  19.   
  20.         [BindProperty]  
  21.         public Entity.Product product { get; set; }  
  22.   
  23.         [TempData]  
  24.         public string Message { get; set; }  
  25.         public void OnGet()  
  26.         {  
  27.             productList = _productRepository.GetList();  
  28.         }  
  29.   
  30.         public IActionResult OnPostDelete(int id)  
  31.         {  
  32.             if (id > 0)  
  33.             {  
  34.                 var count = _productRepository.DeleteProdcut(id);  
  35.                 if (count > 0)  
  36.                 {  
  37.                     Message = "Product Deleted Successfully !";  
  38.                     return RedirectToPage("/Product/Index");  
  39.                 }  
  40.             }  
  41.   
  42.             return Page();  
  43.   
  44.         }  
  45.     }  
  46. }  

Add.cshtml File

This file is responsible to create UI for adding new product with required validation if data does not pass.

  1. @page  
  2. @model RazorPagesExample.Pages.Product.AddModel  
  3. @{  
  4.     ViewData["Title"] = "Add New Product Page";  
  5. }  
  6.   
  7. <div>  
  8.     <div>  
  9.         <div class="modal-content">  
  10.             <div class="modal-header">  
  11.                 <h3 class="modal-title"><strong>New Product</strong></h3>  
  12.             </div>  
  13.             <div class="modal-body">  
  14.                 <div class="row">  
  15.                     <div class="col-md-4 item_img">  
  16.                         <img src="https://www.buehler.ca/images/buttons/Product_Icon.png" class="img-responsive">  
  17.                     </div>  
  18.                     <div class="col-md-8 item_content">  
  19.                         <form method="post">  
  20.                             <h4>  
  21.                                 <span>Please Enter New Product Details!!!</span>  
  22.                             </h4>  
  23.                             <div class="container">  
  24.                                 <div class="row">  
  25.                                     <div class="col-md-4">  
  26.                                         <div class="panel">  
  27.                                             <div class="panel-body">  
  28.                                                 <div class="col-md-12" style="margin-top:15px;">  
  29.                                                     <label asp-for="product.Name" style="font-weight:bold;"></label>  
  30.                                                     <input type='text' class='form-control' asp-for="product.Name" />  
  31.                                                     <span class="alert-danger" asp-validation-for="product.Name"></span>  
  32.                                                 </div>  
  33.                                                 <div class="col-md-12" style="margin-top:15px;">  
  34.                                                     <label asp-for="product.Model"  style="font-weight:bold;"></label>  
  35.                                                     <input type='text' class='form-control' asp-for="product.Model" />  
  36.                                                     <span class="alert-danger" asp-validation-for="product.Model"></span>  
  37.                                                 </div>  
  38.                                                 <div class="col-md-12" style="margin-top:15px;">  
  39.                                                     <label asp-for="product.Price"  style="font-weight:bold;"></label>  
  40.                                                     <input type='text' class='form-control' asp-for="product.Price" />  
  41.                                                     <span class="alert-danger" asp-validation-for="product.Price"></span>  
  42.                                                 </div>  
  43.   
  44.                                                 <div class="text-center col-md-12" style="margin-top:35px;">  
  45.                                                     <button class="btn btn-primary btn-sx" type="submit"><i class="glyphicon glyphicon-plus"></i> Add Product</button>  
  46.                                                     <a class="btn btn-primary btn-sx" asp-page="/Product/Index"><i class="glyphicon glyphicon-backward"></i> Product List</a>  
  47.                                                 </div>  
  48.                                             </div>  
  49.                                         </div>  
  50.                                     </div>  
  51.                                 </div>  
  52.                             </div>  
  53.                         </form>  
  54.                     </div>  
  55.                 </div>  
  56.             </div>  
  57.         </div>  
  58.     </div>  
  59. </div>  

Add.cshtml.cs File

This is code-behind file for Add.cshtml. It has the responsibility to add a new record and record is added successfully then redirect to Product’s home page.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesExample.Repository;  
  4.   
  5. namespace RazorPagesExample.Pages.Product  
  6. {  
  7.     public class AddModel : PageModel  
  8.     {  
  9.         IProductRepository _productRepository;  
  10.         public AddModel(IProductRepository productRepository)  
  11.         {  
  12.             _productRepository = productRepository;  
  13.         }  
  14.   
  15.         [BindProperty]  
  16.         public Entity.Product product { get; set; }  
  17.   
  18.         [TempData]  
  19.         public string Message { get; set; }  
  20.         public IActionResult OnGet()  
  21.         {  
  22.             return Page();  
  23.         }  
  24.         public IActionResult OnPost()  
  25.         {  
  26.             if (ModelState.IsValid)  
  27.             {  
  28.                 var count = _productRepository.Add(product);  
  29.                 if (count > 0)  
  30.                 {  
  31.                     Message = "New Product Added Successfully !";  
  32.                     return RedirectToPage("/Product/Index");  
  33.                 }                  
  34.             }  
  35.   
  36.             return Page();  
  37.         }  
  38.     }  
  39. }  

Edit.cshtml File

This is responsible for editing the existing record and validating the data.

  1. @page "{Id:int}"  
  2. @model RazorPagesExample.Pages.Product.EditModel  
  3. @{  
  4.     ViewData["Title"] = "Product Edit Page";  
  5. }  
  6.   
  7. <div>  
  8.     <div>  
  9.         <div class="modal-content">  
  10.             <div class="modal-header">  
  11.                 <h3 class="modal-title"><strong>Edit Product</strong></h3>  
  12.             </div>  
  13.             <div class="modal-body">  
  14.                 <div class="row">  
  15.                     <div class="col-md-4 item_img">  
  16.                         <img src="https://www.buehler.ca/images/buttons/Product_Icon.png" class="img-responsive">  
  17.                     </div>  
  18.                     <div class="col-md-8 item_content">  
  19.                         <form method="post">  
  20.                             <h4>  
  21.                                 <span>Please Update Product Informations !!!</span>  
  22.                             </h4>  
  23.                             <div class="container">  
  24.                                 <div class="row">  
  25.                                     <div class="col-md-4">  
  26.                                         <div class="panel">  
  27.                                             <div class="panel-body">  
  28.                                                 <div class="col-md-12" style="margin-top:15px;">  
  29.                                                     <input asp-for="product.Id" type="hidden" />  
  30.                                                     <label asp-for="product.Name" style="font-weight:bold;"></label>  
  31.                                                     <input type='text' class='form-control' asp-for="product.Name" />  
  32.                                                     <span class="alert-danger" asp-validation-for="product.Name"></span>  
  33.                                                 </div>  
  34.                                                 <div class="col-md-12" style="margin-top:15px;">  
  35.                                                     <label asp-for="product.Model" style="font-weight:bold;"></label>  
  36.                                                     <input type='text' class='form-control' asp-for="product.Model" />  
  37.                                                     <span class="alert-danger" asp-validation-for="product.Model"></span>  
  38.                                                 </div>  
  39.                                                 <div class="col-md-12" style="margin-top:15px;">  
  40.                                                     <label asp-for="product.Price" style="font-weight:bold;"></label>  
  41.                                                     <input type='text' class='form-control' asp-for="product.Price" />  
  42.                                                     <span class="alert-danger" asp-validation-for="product.Price"></span>  
  43.                                                 </div>  
  44.   
  45.                                                 <div class="text-center col-md-12" style="margin-top:35px;">  
  46.                                                     <button class="btn btn-primary btn-sx" type="submit">  
  47.                                                         <i class="glyphicon glyphicon-edit"></i> Edit Product  
  48.                                                     </button>  
  49.                                                     <a class="btn btn-primary btn-sx" asp-page="/Product/Index"><i class="glyphicon glyphicon-backward"></i> Product List</a>  
  50.                                                 </div>  
  51.                                             </div>  
  52.                                         </div>  
  53.                                     </div>  
  54.                                 </div>  
  55.                             </div>  
  56.                         </form>  
  57.                     </div>  
  58.                 </div>  
  59.             </div>  
  60.         </div>  
  61.     </div>  
  62. </div>  

Edit.cshtml.cs File

This file is basically code-behind for Edit.cshtml file and contains the code to edit the existing record and return to Product’s home page if record is edited successfully.

  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.AspNetCore.Mvc.RazorPages;  
  3. using RazorPagesExample.Repository;  
  4.   
  5. namespace RazorPagesExample.Pages.Product  
  6. {  
  7.     public class EditModel : PageModel  
  8.     {  
  9.         IProductRepository _productRepository;  
  10.         public EditModel(IProductRepository productRepository)  
  11.         {  
  12.             _productRepository = productRepository;  
  13.         }  
  14.   
  15.   
  16.         [BindProperty]  
  17.         public Entity.Product product { get; set; }  
  18.   
  19.         public void OnGet(int id)  
  20.         {  
  21.             product = _productRepository.GetProduct(id);              
  22.         }  
  23.   
  24.         public IActionResult OnPost()  
  25.         {  
  26.             var data = product;  
  27.   
  28.             if (ModelState.IsValid)  
  29.             {  
  30.                 var count = _productRepository.EditProduct(data);  
  31.                 if (count > 0)  
  32.                 {  
  33.                     return RedirectToPage("/Product/Index");  
  34.                 }  
  35.             }  
  36.   
  37.             return Page();  
  38.         }  
  39.     }  
  40. }  

As you have noticed two things with above .cs file that we are using product dependency injection as following code shown.

  1. IProductRepository _productRepository;  
  2.       public EditModel(IProductRepository productRepository)  
  3.       {  
  4.           _productRepository = productRepository;  
  5.       }  

Apart from that to bind the data automatically with model, we are using [BindProperty] attribute with the property as follows.

  1. [BindProperty]  
  2. public Entity.Product product { get; set; }  

Finally everything has been set up and now we can run the application. To run the application just press F5 and the application is ready for you.

You have to go to the following URL to perform CRUD operations for Product.

http://localhost:51068/product

Asp.Net Core

To Add New Product, just click to Add New Product button and it will open Add page as follows. If you don’t fill required data and press “Add Product” button it will show the error as well.

Asp.Net Core

You can perform Edit and Delete operations using Edit and Delete button at last in the product list view.

Conclusion

So, today we have learned how to perform CRUD operations with Asp.Net Core 2.0 Razor Page using Dapper and Repository Pattern.

I hope this post will help you. Please leave your feedback which helps me to improve for the next post. If you have any doubts please ask queries in the comment section and If you like this post, please share it with your friends. Thanks