Razor Page Web Application With ASP.NET Core Using ADO.NET

Introduction

In this article, I am going to explain how to create a web application in ASP.NET Core using Razor pages and ADO.NET. We will be creating a sample Employees Record Management System.

We will be using Visual Studio 2017 (Version 15.3.5 or above) and SQL Server.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install Visual Studio 2017 Community Edition (Version 15.3.5 or above) from here

Now, we are ready to proceed with the creation of our web application.

Creating Table and Stored Procedures

We will be using a DB table to store all the records of employees.

Open SQL Server and use the following script to create tblEmployee table.

  1. Create table tblEmployee(  
  2.     EmployeeId int IDENTITY(1,1) NOT NULL,  
  3.     Name varchar(20) NULL,  
  4.     City varchar(20) NULL,  
  5.     Department varchar(20) NULL,  
  6.     Gender varchar(6) NULL  
  7. )   

Now, we will create stored procedures to add, delete, update, and get employee data.

To insert an Employee Record

  1. Create procedure spAddEmployee   
  2. (  
  3.     @Name VARCHAR(20),   
  4.     @City VARCHAR(20),  
  5.     @Department VARCHAR(20),  
  6.     @Gender VARCHAR(6)  
  7. )  
  8. as   
  9. Begin   
  10.     Insert into tblEmployee (Name,City,Department, Gender)   
  11.     Values (@Name,@City,@Department, @Gender)   
  12. End   

To update an Employee Record

  1. Create procedure spUpdateEmployee    
  2. (    
  3.    @EmpId INTEGER ,  
  4.    @Name VARCHAR(20),   
  5.    @City VARCHAR(20),  
  6.    @Department VARCHAR(20),  
  7.    @Gender VARCHAR(6)  
  8. )    
  9. as    
  10. begin    
  11.    Update tblEmployee     
  12.    set Name=@Name,    
  13.    City=@City,    
  14.    Department=@Department,  
  15.    Gender=@Gender    
  16.    where EmployeeId=@EmpId    
  17. End   
To delete an Employee Record
  1. Create procedure spDeleteEmployee   
  2. (    
  3.    @EmpId int    
  4. )    
  5. as     
  6. begin    
  7.    Delete from tblEmployee where EmployeeId=@EmpId    
  8. End   

To view all Employee Records

  1. Create procedure spGetAllEmployees  
  2. as  
  3. Begin  
  4.     Select *  
  5.     from tblEmployee  
  6. End  
Now, our Database part is completed. So, we will move on to create the web application with Visual Studio.

Create Razor Page Web Application

Open Visual Studio and select File >> New >> Project.

 

After selecting the project, a new dialog will open. Select .NET Core inside Visual C# menu from the left panel.

Then, select “ASP.NET Core Web Application” from available project types. Put the name of project as EmployeeDemo and press OK. Refer to this image.

After clicking on OK, a new dialog will open asking to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Web application” template.

 

Now, our project will open. You can see the project files in Solution Explorer. Note that there are no Model, View, and Controller folders by default but we do have a Pages folder which contains all the default Razor pages. We will be creating our own Razor pages inside this folder.

 
Adding A Model to the Application

We will add a folder with name Models inside our project. Right click on Project and select Add >> New Folder. A new folder will be created inside the project. Rename it as Models.

 

Now, we will be adding our class files to Models folder. Right click on Models folder and select Add >> Class. Name your class Employee.cs. This class will contain our Employee model properties.

Add one more class file to Models folder. Name it as EmployeeDataAccessLayer.cs . This class will contain our Database related operations.

Now, the Models folders has the following structure.

 

Open Employee.cs and put the following code in it. Since we are adding the required validators to the fields of Employee class, so we need to use System.ComponentModel.DataAnnotations at the top.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Threading.Tasks;    
  5. using System.ComponentModel.DataAnnotations;    
  6.     
  7. namespace EmployeeDemo.Models    
  8. {    
  9.     public class Employee    
  10.     {    
  11.         public int ID { get; set; }    
  12.         [Required]    
  13.         public string Name { get; set; }    
  14.         [Required]    
  15.         public string Gender { get; set; }    
  16.         [Required]    
  17.         public string Department { get; set; }    
  18.         [Required]    
  19.         public string City { get; set; }    
  20.     }    
  21. }     

Open EmployeeDataAccessLayer.cs and put the following code to handle database operations. Make sure to put your connection string.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5.   
  6. namespace EmployeeDemo.Models  
  7. {  
  8.     public class EmployeeDataAccessLayer  
  9.     {  
  10.         string connectionString = "Your Connection string here";  
  11.   
  12.         //To View all employees details    
  13.         public IEnumerable<Employee> GetAllEmployees()  
  14.         {  
  15.             List<Employee> lstemployee = new List<Employee>();  
  16.   
  17.             using (SqlConnection con = new SqlConnection(connectionString))  
  18.             {  
  19.                 SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);  
  20.                 cmd.CommandType = CommandType.StoredProcedure;  
  21.   
  22.                 con.Open();  
  23.                 SqlDataReader rdr = cmd.ExecuteReader();  
  24.   
  25.                 while (rdr.Read())  
  26.                 {  
  27.                     Employee employee = new Employee();  
  28.   
  29.                     employee.ID = Convert.ToInt32(rdr["EmployeeID"]);  
  30.                     employee.Name = rdr["Name"].ToString();  
  31.                     employee.Gender = rdr["Gender"].ToString();  
  32.                     employee.Department = rdr["Department"].ToString();  
  33.                     employee.City = rdr["City"].ToString();  
  34.   
  35.                     lstemployee.Add(employee);  
  36.                 }  
  37.                 con.Close();  
  38.             }  
  39.             return lstemployee;  
  40.         }  
  41.   
  42.         //To Add new employee record    
  43.         public void AddEmployee(Employee employee)  
  44.         {  
  45.             using (SqlConnection con = new SqlConnection(connectionString))  
  46.             {  
  47.                 SqlCommand cmd = new SqlCommand("spAddEmployee", con);  
  48.                 cmd.CommandType = CommandType.StoredProcedure;  
  49.   
  50.                 cmd.Parameters.AddWithValue("@Name", employee.Name);  
  51.                 cmd.Parameters.AddWithValue("@Gender", employee.Gender);  
  52.                 cmd.Parameters.AddWithValue("@Department", employee.Department);  
  53.                 cmd.Parameters.AddWithValue("@City", employee.City);  
  54.   
  55.                 con.Open();  
  56.                 cmd.ExecuteNonQuery();  
  57.                 con.Close();  
  58.             }  
  59.         }  
  60.   
  61.         //To Update the records of a particluar employee  
  62.         public void UpdateEmployee(Employee employee)  
  63.         {  
  64.             using (SqlConnection con = new SqlConnection(connectionString))  
  65.             {  
  66.                 SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);  
  67.                 cmd.CommandType = CommandType.StoredProcedure;  
  68.   
  69.                 cmd.Parameters.AddWithValue("@EmpId", employee.ID);  
  70.                 cmd.Parameters.AddWithValue("@Name", employee.Name);  
  71.                 cmd.Parameters.AddWithValue("@Gender", employee.Gender);  
  72.                 cmd.Parameters.AddWithValue("@Department", employee.Department);  
  73.                 cmd.Parameters.AddWithValue("@City", employee.City);  
  74.   
  75.                 con.Open();  
  76.                 cmd.ExecuteNonQuery();  
  77.                 con.Close();  
  78.             }  
  79.         }  
  80.   
  81.         //Get the details of a particular employee  
  82.         public Employee GetEmployeeData(int? id)  
  83.         {  
  84.             Employee employee = new Employee();  
  85.   
  86.             using (SqlConnection con = new SqlConnection(connectionString))  
  87.             {  
  88.                 string sqlQuery = "SELECT * FROM tblEmployee WHERE EmployeeID= " + id;  
  89.                 SqlCommand cmd = new SqlCommand(sqlQuery, con);  
  90.   
  91.                 con.Open();  
  92.                 SqlDataReader rdr = cmd.ExecuteReader();  
  93.   
  94.                 while (rdr.Read())  
  95.                 {  
  96.                     employee.ID = Convert.ToInt32(rdr["EmployeeID"]);  
  97.                     employee.Name = rdr["Name"].ToString();  
  98.                     employee.Gender = rdr["Gender"].ToString();  
  99.                     employee.Department = rdr["Department"].ToString();  
  100.                     employee.City = rdr["City"].ToString();  
  101.                 }  
  102.             }  
  103.             return employee;  
  104.         }  
  105.   
  106.         //To Delete the record on a particular employee  
  107.         public void DeleteEmployee(int? id)  
  108.         {  
  109.   
  110.             using (SqlConnection con = new SqlConnection(connectionString))  
  111.             {  
  112.                 SqlCommand cmd = new SqlCommand("spDeleteEmployee", con);  
  113.                 cmd.CommandType = CommandType.StoredProcedure;  
  114.   
  115.                 cmd.Parameters.AddWithValue("@EmpId", id);  
  116.   
  117.                 con.Open();  
  118.                 cmd.ExecuteNonQuery();  
  119.                 con.Close();  
  120.             }  
  121.         }  
  122.     }  
  123. }  

Now, we will proceed to create our Razor pages.

Adding Razor Pages

First, we will be creating a page to create Employee records and as I have mentioned we will be adding our Razor pages inside Pages folder, just right click on Pages folder and select Add >> New item. 



A new dialog box will open. Select ASP.NET Core from the left panel, then select “Razor Pages” from templates panel, and put the name as CreateEmployee.cshtml. Press OK. 

 

Now, you can observe that our Razor page has been added to Pages folder. You can also observe that the Razor page has code behind file with extension .cshtml.cs also, just the same as webforms (aspx.cs). The code behind page will be used to handle business logic.

Similarly, we will add 4 more Razor pages to Pages folder, DeleteEmployee.cshtml, EditEmployee.cshtml, EmployeeDetails.cshtml andEmployeeIndex.cshtml to perform the CRUD operations.

Now, our Pages folder will look like this showing all the five newly created Razor pages. 

 
Now, the pages have been created, so we will put codes in them.

Create Employee

In this Razor page, we will be creating a new employee record.

Open CreateEmployee.cshtml and put the following code in it.
  1. @page  
  2. @model CreateEmployeeModel  
  3. @{  
  4.     ViewData["Title"] = "Create";  
  5. }  
  6.   
  7. <h2>Create Employee Record</h2>  
  8. <hr />  
  9. <div class="row">  
  10.     <div class="col-md-4">  
  11.         <form method="post">  
  12.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  13.             <div class="form-group">  
  14.                 <label asp-for="employee.Name" class="control-label"></label>  
  15.                 <input asp-for="employee.Name" class="form-control" />  
  16.                 <span asp-validation-for="employee.Name" class="text-danger"></span>  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label asp-for="employee.Gender" class="control-label"></label>  
  20.                 <select asp-for="employee.Gender" class="form-control">  
  21.                     <option value="">-- Select Gender --</option>  
  22.                     <option value="Male">Male</option>  
  23.                     <option value="Female">Female</option>  
  24.                 </select>                  
  25.                 <span asp-validation-for="employee.Gender" class="text-danger"></span>  
  26.             </div>  
  27.             <div class="form-group">  
  28.                 <label asp-for="employee.Department" class="control-label"></label>  
  29.                 <input asp-for="employee.Department" class="form-control" />  
  30.                 <span asp-validation-for="employee.Department" class="text-danger"></span>  
  31.             </div>  
  32.             <div class="form-group">  
  33.                 <label asp-for="employee.City" class="control-label"></label>  
  34.                 <input asp-for="employee.City" class="form-control" />  
  35.                 <span asp-validation-for="employee.City" class="text-danger"></span>  
  36.             </div>  
  37.             <div class="form-group">  
  38.                 <input type="submit" value="Create" class="btn btn-default" />  
  39.             </div>  
  40.         </form>  
  41.     </div>  
  42. </div>  
  43. <div>  
  44.     <a asp-page="EmployeeIndex">Back to List</a>  
  45. </div>  
  46. @section Scripts {  
  47.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  48. }  
Open CreateEmployee.cshtml.cs and put the following code in it.
  1. using System;  
  2. using System.Collections.Generic;   
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.AspNetCore.Mvc.RazorPages;  
  5. using EmployeeDemo.Models;  
  6.   
  7. namespace EmployeeDemo.Pages  
  8. {  
  9.     public class CreateEmployeeModel : PageModel  
  10.     {  
  11.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  12.   
  13.         [BindProperty]  
  14.         public Employee employee { getset; }  
  15.   
  16.         public ActionResult OnPost()  
  17.         {  
  18.             if (!ModelState.IsValid)  
  19.             {  
  20.                 return Page();  
  21.             }  
  22.   
  23.             objemployee.AddEmployee(employee);  
  24.   
  25.             return RedirectToPage("./EmployeeIndex");  
  26.         }  
  27.     }  
  28. }  

You can observe that we are using [BindProperty] attribute on employee object we have created in CreateEmployee.cshtml.cs file. This will help to capture the data posted by the form in our object. If we remove [BindProperty] attribute, then the employee object will be null as it won’t capture any data from post request.

Employee index

In this Razor page, we will be displaying all the employee records available in the database. Additionally, we will be providing action methods Edit, Delete, and View on each record.

Open EmployeeIndex.cshtml and put the following code in it. 
  1. @page  
  2. @model EmployeeIndexModel  
  3. @{  
  4.     ViewData["Title"] = "Index";  
  5. }  
  6. <h2>Index</h2>  
  7. <p>  
  8.     <a asp-page="CreateEmployee">Create New</a>  
  9. </p>  
  10. <table class="table">  
  11.     <thead>  
  12.         <tr>  
  13.             <th>  
  14.                 @Html.DisplayNameFor(model => model.employee[0].ID)  
  15.             </th>  
  16.             <th>  
  17.                 @Html.DisplayNameFor(model => model.employee[0].Name)  
  18.             </th>  
  19.             <th>  
  20.                 @Html.DisplayNameFor(model => model.employee[0].Gender)  
  21.             </th>  
  22.             <th>  
  23.                 @Html.DisplayNameFor(model => model.employee[0].Department)  
  24.             </th>  
  25.             <th>  
  26.                 @Html.DisplayNameFor(model => model.employee[0].City)  
  27.             </th>  
  28.             <th></th>  
  29.         </tr>  
  30.     </thead>  
  31.     <tbody>  
  32.         @foreach (var item in Model.employee)  
  33.         {  
  34.             <tr>  
  35.                 <td>  
  36.                     @Html.DisplayFor(modelItem => item.ID)  
  37.                 </td>  
  38.                 <td>  
  39.                     @Html.DisplayFor(modelItem => item.Name)  
  40.                 </td>  
  41.                 <td>  
  42.                     @Html.DisplayFor(modelItem => item.Gender)  
  43.                 </td>  
  44.                 <td>  
  45.                     @Html.DisplayFor(modelItem => item.Department)  
  46.                 </td>  
  47.                 <td>  
  48.                     @Html.DisplayFor(modelItem => item.City)  
  49.                 </td>  
  50.                 <td>  
  51.                     <a asp-page="./EditEmployee" asp-route-id="@item.ID">Edit</a> |  
  52.                     <a asp-page="./EmployeeDetails" asp-route-id="@item.ID">Details</a> |  
  53.                     <a asp-page="./DeleteEmployee" asp-route-id="@item.ID">Delete</a>  
  54.                 </td>  
  55.             </tr>  
  56.         }  
  57.     </tbody>  
  58. </table>  

Open EmployeeIndex.cshtml.cs and put the following code in it.

  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 EmployeeDemo.Models;  
  8.   
  9. namespace EmployeeDemo.Pages  
  10. {  
  11.     public class EmployeeIndexModel : PageModel  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.         public List<Employee> employee { getset; }  
  15.   
  16.         public void OnGet()  
  17.         {  
  18.             employee = objemployee.GetAllEmployees().ToList();  
  19.         }  
  20.     }  
  21. }  

Employee Details

In this Razor page, we will be displaying the details of a particular employee. This page can be invoked by clicking on Details action method on EmployeeIndex page.

Open EmployeeDetails.cshtml and put the following code in it.

  1. @page  
  2. @model EmployeeDetailsModel  
  3.   
  4. @{  
  5.     ViewData["Title"] = "Details";  
  6. }  
  7.   
  8. <div>  
  9.     <h4>Employee</h4>  
  10.     <hr />  
  11.     <dl class="dl-horizontal">  
  12.         <dt>  
  13.             @Html.DisplayNameFor(model => model.employee.Name)  
  14.         </dt>  
  15.         <dd>  
  16.             @Html.DisplayFor(model => model.employee.Name)  
  17.         </dd>  
  18.         <dt>  
  19.             @Html.DisplayNameFor(model => model.employee.Gender)  
  20.         </dt>  
  21.         <dd>  
  22.             @Html.DisplayFor(model => model.employee.Gender)  
  23.         </dd>  
  24.         <dt>  
  25.             @Html.DisplayNameFor(model => model.employee.Department)  
  26.         </dt>  
  27.         <dd>  
  28.             @Html.DisplayFor(model => model.employee.Department)  
  29.         </dd>  
  30.         <dt>  
  31.             @Html.DisplayNameFor(model => model.employee.City)  
  32.         </dt>  
  33.         <dd>  
  34.             @Html.DisplayFor(model => model.employee.City)  
  35.         </dd>  
  36.     </dl>  
  37. </div>  
  38. <div>  
  39.     <a asp-page="./EditEmployee" asp-route-id="@Model.employee.ID">Edit</a> |  
  40.     <a asp-page="./EmployeeIndex">Back to List</a>  
  41. </div>  

Open EmployeeDetails.cshtml.cs and put the following code in it.

  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 EmployeeDemo.Models;    
  8.     
  9. namespace EmployeeDemo.Pages    
  10. {    
  11.     public class EmployeeDetailsModel : PageModel    
  12.     {    
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();           
  14.         public Employee employee { getset; }   
  15.           
  16.         public ActionResult OnGet(int? id)    
  17.         {    
  18.             if (id == null)    
  19.             {    
  20.                 return NotFound();    
  21.             }    
  22.             employee = objemployee.GetEmployeeData(id);    
  23.     
  24.             if (employee == null)    
  25.             {    
  26.                 return NotFound();    
  27.             }    
  28.             return Page();    
  29.         }    
  30.     }    
  31. }     

Edit Employee

This Razor page will enable us to edit the record of an existing employee. This page can be invoked by clicking on Edit action method on EmployeeIndex page.

Open EditEmployee.cshtml and put the following code in it.

  1. @page  
  2. @model EditEmployeeModel  
  3. @{  
  4.     ViewData["Title"] = "Edit";  
  5. }  
  6.   
  7. <h2>Edit</h2>  
  8. <h4>Employee</h4>  
  9. <hr />  
  10. <div class="row">  
  11.     <div class="col-md-4">  
  12.         <form method="post">  
  13.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  14.             <input type="hidden" asp-for="employee.ID" />  
  15.             <div class="form-group">  
  16.                 <label asp-for="employee.Name" class="control-label"></label>  
  17.                 <input asp-for="employee.Name" class="form-control" />  
  18.                 <span asp-validation-for="employee.Name" class="text-danger"></span>  
  19.             </div>  
  20.             <div class="form-group">  
  21.                 <label asp-for="employee.Gender" class="control-label"></label>  
  22.                 <select asp-for="employee.Gender" class="form-control">  
  23.                     <option value="">-- Select Gender --</option>  
  24.                     <option value="Male">Male</option>  
  25.                     <option value="Female">Female</option>  
  26.                 </select>  
  27.                 <span asp-validation-for="employee.Gender" class="text-danger"></span>  
  28.             </div>  
  29.             <div class="form-group">  
  30.                 <label asp-for="employee.Department" class="control-label"></label>  
  31.                 <input asp-for="employee.Department" class="form-control" />  
  32.                 <span asp-validation-for="employee.Department" class="text-danger"></span>  
  33.             </div>  
  34.             <div class="form-group">  
  35.                 <label asp-for="employee.City" class="control-label"></label>  
  36.                 <input asp-for="employee.City" class="form-control" />  
  37.                 <span asp-validation-for="employee.City" class="text-danger"></span>  
  38.             </div>  
  39.             <div class="form-group">  
  40.                 <input type="submit" value="Save" class="btn btn-default" />  
  41.             </div>  
  42.         </form>  
  43.     </div>  
  44. </div>  
  45. <div>  
  46.     <a asp-page="./EmployeeIndex">Back to List</a>  
  47. </div>  
  48. @section Scripts {  
  49.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  50. }  

Open EditEmployee.cshtml.cs and put the following code in it.

  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 EmployeeDemo.Models;  
  8.   
  9. namespace EmployeeDemo.Pages  
  10. {  
  11.     public class EditEmployeeModel : PageModel  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.   
  15.         [BindProperty]  
  16.         public Employee employee { getset; }  
  17.   
  18.         public ActionResult OnGet(int? id)  
  19.         {  
  20.             if (id == null)  
  21.             {  
  22.                 return NotFound();  
  23.             }  
  24.             employee = objemployee.GetEmployeeData(id);  
  25.   
  26.             if (employee == null)  
  27.             {  
  28.                 return NotFound();  
  29.             }  
  30.             return Page();  
  31.         }  
  32.   
  33.         public ActionResult OnPost()  
  34.         {  
  35.             if (!ModelState.IsValid)  
  36.             {  
  37.                 return Page();  
  38.             }  
  39.             objemployee.UpdateEmployee(employee);  
  40.   
  41.             return RedirectToPage("./EmployeeIndex");  
  42.         }  
  43.     }  
  44. }  

Delete Employee

This Razor page will enable us to delete the record of an existing employee. This page can be invoked by clicking on Delete action method on EmployeeIndex page

Open DeleteEmployee.cshtml and put the following code in it.
  1. @page  
  2. @model DeleteEmployeeModel  
  3.   
  4. @{  
  5.     ViewData["Title"] = "Delete";  
  6. }  
  7.   
  8. <h2>Delete</h2>  
  9. <h3>Are you sure you want to delete this?</h3>  
  10. <div>  
  11.     <h4>Employee</h4>  
  12.     <hr />  
  13.     <dl class="dl-horizontal">  
  14.         <dt>  
  15.             @Html.DisplayNameFor(model => model.employee.Name)  
  16.         </dt>  
  17.         <dd>  
  18.             @Html.DisplayFor(model => model.employee.Name)  
  19.         </dd>  
  20.         <dt>  
  21.             @Html.DisplayNameFor(model => model.employee.Gender)  
  22.         </dt>  
  23.         <dd>  
  24.             @Html.DisplayFor(model => model.employee.Gender)  
  25.         </dd>  
  26.         <dt>  
  27.             @Html.DisplayNameFor(model => model.employee.Department)  
  28.         </dt>  
  29.         <dd>  
  30.             @Html.DisplayFor(model => model.employee.Department)  
  31.         </dd>  
  32.         <dt>  
  33.             @Html.DisplayNameFor(model => model.employee.City)  
  34.         </dt>  
  35.         <dd>  
  36.             @Html.DisplayFor(model => model.employee.City)  
  37.         </dd>  
  38.     </dl>  
  39.   
  40.     <form method="post">  
  41.         <input type="hidden" asp-for="employee.ID" />  
  42.         <input type="submit" value="Delete" class="btn btn-default" /> |  
  43.         <a asp-page="./EmployeeIndex">Back to List</a>  
  44.     </form>  
  45. </div>  

Open DeleteEmployee.cshtml.cs and put the following code in it.

  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 EmployeeDemo.Models;  
  8.   
  9. namespace EmployeeDemo.Pages  
  10. {  
  11.     public class DeleteEmployeeModel : PageModel  
  12.     {  
  13.         EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();  
  14.   
  15.         public Employee employee { getset; }  
  16.   
  17.         public ActionResult OnGet(int? id)  
  18.         {  
  19.             if (id == null)  
  20.             {  
  21.                 return NotFound();  
  22.             }  
  23.             employee = objemployee.GetEmployeeData(id);  
  24.   
  25.             if (employee == null)  
  26.             {  
  27.                 return NotFound();  
  28.             }  
  29.             return Page();  
  30.         }  
  31.   
  32.         public ActionResult OnPost(int? id)  
  33.         {  
  34.             if (id == null)  
  35.             {  
  36.                 return NotFound();  
  37.             }  
  38.   
  39.             objemployee.DeleteEmployee(id);  
  40.   
  41.             return RedirectToPage("./EmployeeIndex");  
  42.         }  
  43.     }  
  44. }  

Note that we have two methods, OnGet and OnPost in DeleteEmployee.cshtml.cs. When we click on Delete link on the EmployeeIndex page, it will send a Get request and return a View of the employee using OnGet method. When we click on Delete button on this page, it will send a Post request to delete the record which is handled by the OnPost method. Performing a delete operation in response to a Get request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole. Hence we have two separate methods.

And that’s it. We have created our first ASP.NET Core application using Razor pages. Now, we will proceed to perform CRUD operations.

Launch the application and to access any page, put the Razor page name in the URL. Open EmployeeIndex page as http://localhost:xxxx/EmployeeIndex 

You can see the page as shown below.

 
Click on CreateNew to create a new Employee record. Add a new Employee record as shown in the image below.
 
If we miss the data in any field while creating employee record, we will get a required field validation error message.
 
After inserting the data in all the fields, click on "Create" button. The new employee record will be created and you will be redirected to the EmployeeIndex page, having records of all the employees. Here, we can also see action methods Edit, Details and Delete.
 

 The corresponding records in Database will be like this



If we want to edit an existing employee record, then click on Edit action link. It will open EditEmployee page as below where we can change the employee data.

Here, we have changed the city of an employee named Ankit from Delhi to Kolkata. Click on "Save" to return to the EmployeeIndex page to see the updated changes as highlighted in the image below.

 

If we miss any fields while editing employee records, then the Edit page will also throw required field validation error message.

 
If you want to see the details of any Employee, then click on Details action link, which will open the EmployeeDetails page as shown in the image below.
 
Click on "Back to List" to go back to the EmployeeIndex page. Now, we will perform Delete operation on an employee named Mahesh. Click on Delete action link which will open DeleteEmployee page asking for a confirmation to delete.

 
Once we click on Delete button, the employee record gets deleted and we will be redirected to the Employee Index page. Here, we can see that the employee with name Mahesh has been removed from our record.

 
Conclusion

We have learned how to create a Razor page web application with ASP.NET Core using ADO.NET. We have also performed CRUD operations on it. Please refer to the attached code for better understanding.

Up Next
    Ebook Download
    View all
    Learn
    View all