CRUD Operation In ASP.NET Core 2.0 With Razor Pages Using ADO.NET

In this article, we will learn CRUD operation in ASP.NET Core 2.0 with Razor pages using ADO.NET step by step. 

ASP.NET Core


We will use Visual Studio 2017 to develop the web application using ASP.NET Core 2.0 with Razor pages. If you don’t have a basic idea of ASP.NET Core and how to set up ASP.NET Core Environment, or want to know how to install Visual Studio 2017, please go to my previous article and click What ASP.NET Core Is And set up ASP.NET Core Environment.

Prerequisites
f
  • Install .NET Core 2.0.0 or above SDK steps to install click on the link .NET Core 2.0.
  • Install Visual Studio 2017 and steps to install click on the link Visual Studio 2017.
  • SQL Server 2008 or above.

We will create one small "Group Meeting" web application using ASP.NET Core 2.0. as following. 

First of all, create a database script using SQL Server.

Scripts 1 

To create the database.

  1. CREATE DATABASE ProjectMeeting  

 

Scripts 2

To create the database table named as “GroupMeeting”.

  1. USE [ProjectMeeting]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[GroupMeeting]    Script Date: 27/07/2018 00:47:57 ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[GroupMeeting](  
  15.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  16.     [ProjectName] [varchar](50) NULL,  
  17.     [GroupMeetingLeadName] [varchar](50) NULL,  
  18.     [TeamLeadName] [varchar](50) NULL,  
  19.     [Description] [varchar](50) NULL,  
  20.     [GroupMeetingDate] [dateNULL,  
  21.  CONSTRAINT [PK_GroupMeeting-2] PRIMARY KEY CLUSTERED   
  22. (  
  23.     [Id] ASC  
  24. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  25. ON [PRIMARY]  
  26.   
  27. GO  
  28.   
  29. SET ANSI_PADDING OFF  
  30. GO  

Scripts 3

Create the stored procedure to get all the group meetings in detail. 

  1. Create procedure [dbo].[GetGroupMeetingDetails]  
  2. AS  
  3. BEGIN  
  4.      SELECT * FROM GROUPMEETING  
  5. END  

Scripts 4

Create the stored procedure to get the group meeting by Id.

  1. Create procedure [dbo].[GetGroupMeetingByID](@Id int)  
  2. AS  
  3. BEGIN  
  4.      SELECT * FROM GROUPMEETING where id=@Id  
  5. END  
Scripts 5

Create the stored procedure to create a new group meeting.
  1. create procedure [dbo].[InsertGroupMeeting]  
  2. (  
  3.     @ProjectName varchar(50),  
  4.     @GroupMeetingLeadName varchar(50),  
  5.     @TeamLeadName varchar(50),  
  6.     @Description varchar(50),  
  7.     @GroupMeetingDate date  
  8. )  
  9. As  
  10. BEGIN  
  11.   
  12.  INSERT INTO GroupMeeting(ProjectName,GroupMeetingLeadName,TeamLeadName,Description,GroupMeetingDate)  
  13.  VALUES(@ProjectName,@GroupMeetingLeadName,@TeamLeadName,@Description,@GroupMeetingDate)  
  14.   
  15. END  

Scripts 6

Create the stored procedure to update the group meeting.

  1. create procedure [dbo].[UpdateGroupMeeting]  
  2. (  
  3.     @Id int,  
  4.     @ProjectName varchar(50),  
  5.     @GroupMeetingLeadName varchar(50),  
  6.     @TeamLeadName varchar(50),  
  7.     @Description varchar(50),  
  8.     @GroupMeetingDate date  
  9. )  
  10. As  
  11. BEGIN  
  12.      UPDATE GroupMeeting  
  13.      SET ProjectName =@ProjectName,  
  14.      GroupMeetingLeadName =@GroupMeetingLeadName,  
  15.      TeamLeadName = @TeamLeadName,  
  16.      Description = @Description,  
  17.      GroupMeetingDate =@GroupMeetingDate  
  18.      Where Id=@Id  
  19. END  

Scripts 7

Create the stored procedure to delete the group meeting. 

  1. create procedure [dbo].[DeleteGroupMeeting]  
  2. (  
  3.     @Id int   
  4. )  
  5. As  
  6. BEGIN  
  7.     DELETE FROM GroupMeeting WHERE Id=@Id  
  8. END  
Now, we have completed our database related changes. Let’s go with the code base changes using Visual Studio 2017.

Step 1

Open Visual Studio 2017.

ASP.NET Core

Step 2

Click on File => Open => New Project, as shown in the image.

 ASP.NET Core

Step 3

Select .NET Core from the left side and select the ‘ASP.NET Core Web Application’ from the new open project template. Then, provide the a meaningful name like “GroupMeetingASP.NETCoreWebApp”.

ASP.NET Core 

Step 4

Select Web Application(MVC) template from the list of templates and click on "OK" button as follows.

 ASP.NET Core

Step 5

The default ASP.NET Core MVC structure gets created as follows. The default model, view and controller folders get created with some default pages. So we will keep as it is the default controller and Views. I will add a new controller as per the requirement.

ASP.NET Core
Step 6

Right click on Models => Click on Add => Click on Class.

ASP.NET Core 

Step 7

Provide a meaningful name like “GroupMeeting” and click on "Add" button as follow.

ASP.NET Core 

Step 8

Write code to create properties for group meeting class as follow. Also, use the required attribute to validate the class fields. Also, we have taken connection string in using string variable OR you can read from appSettings.json file.
  1. public class GroupMeeting  
  2.     {  
  3.         public int GroupMeetingId { getset; }  
  4.         [Required(ErrorMessage ="Enter Project Name!")]  
  5.         public string ProjectName { getset; }  
  6.   
  7.         [Required(ErrorMessage = "Enter Group Lead Name!")]  
  8.         public string GroupMeetingLeadName { getset; }  
  9.         [Required(ErrorMessage = "Enter Team Lead Name!")]  
  10.         public string TeamLeadName { getset; }  
  11.         [Required(ErrorMessage = "Enter Description!")]  
  12.         public string Description { getset; }  
  13.         [Required(ErrorMessage = "Enter Group Meeting Date!")]  
  14.         public DateTime GroupMeetingDate { getset; }  
  15.   
  16.         static string strConnectionString = "User Id=sa;Password=Shri;Server=Shri\\SQL2014;Database=ProjectMeeting;";  
  17.   
  18. }  
Step 9

Write code to get all group meeting details from the database using the stored procedure. The method name is "GetGroupMeetings()" and return type is IEnumerable<GroupMeeting> or List<GroupMeeting> you can use either one of them. 
  1. public static IEnumerable<GroupMeeting> GetGroupMeetings()  
  2.         {  
  3.             List<GroupMeeting> groupMeetingsList = new List<GroupMeeting>();  
  4.             using (SqlConnection con = new SqlConnection(strConnectionString))  
  5.             {  
  6.                 SqlCommand command = new SqlCommand("GetGroupMeetingDetails", con);  
  7.                 command.CommandType = CommandType.StoredProcedure;  
  8.                 if (con.State == ConnectionState.Closed)  
  9.                     con.Open();  
  10.   
  11.                SqlDataReader dataReader= command.ExecuteReader();  
  12.                 while (dataReader.Read())  
  13.                 {  
  14.                     GroupMeeting groupMeeting = new GroupMeeting();  
  15.                     groupMeeting.GroupMeetingId = Convert.ToInt32(dataReader["Id"]);  
  16.                     groupMeeting.ProjectName = dataReader["ProjectName"].ToString();  
  17.                     groupMeeting.GroupMeetingLeadName = dataReader["GroupMeetingLeadName"].ToString();  
  18.                     groupMeeting.TeamLeadName = dataReader["TeamLeadName"].ToString();  
  19.                     groupMeeting.Description = dataReader["Description"].ToString();  
  20.                     groupMeeting.GroupMeetingDate = Convert.ToDateTime(dataReader["GroupMeetingDate"]);  
  21.                     groupMeetingsList.Add(groupMeeting);  
  22.                 }  
  23.             }  
  24.             return groupMeetingsList;  
  25.         }  

Write code to get group meeting detail by groupId using ADO.NET as follows.

  1. public static GroupMeeting GetGroupMeetingById(int? id)  
  2.         {  
  3.             GroupMeeting groupMeeting = new GroupMeeting();  
  4.             if (id == null)  
  5.                 return groupMeeting;  
  6.   
  7.             using (SqlConnection con = new SqlConnection(strConnectionString))  
  8.             {  
  9.                 SqlCommand command = new SqlCommand("GetGroupMeetingByID", con);  
  10.                 command.CommandType = CommandType.StoredProcedure;  
  11.                 command.Parameters.AddWithValue("@Id", id);  
  12.                 if (con.State == ConnectionState.Closed)  
  13.                     con.Open();  
  14.   
  15.                 SqlDataReader dataReader = command.ExecuteReader();  
  16.                 while (dataReader.Read())  
  17.                 {                      
  18.                     groupMeeting.GroupMeetingId = Convert.ToInt32(dataReader["Id"]);  
  19.                     groupMeeting.ProjectName = dataReader["ProjectName"].ToString();  
  20.                     groupMeeting.GroupMeetingLeadName = dataReader["GroupMeetingLeadName"].ToString();  
  21.                     groupMeeting.TeamLeadName = dataReader["TeamLeadName"].ToString();  
  22.                     groupMeeting.Description = dataReader["Description"].ToString();  
  23.                     groupMeeting.GroupMeetingDate = Convert.ToDateTime(dataReader["GroupMeetingDate"]);                   
  24.                 }  
  25.             }  
  26.             return groupMeeting;  
  27.         }  

Step 10

Code to insert the group meeting into the database using ADO.NET is below.

  1. public static int AddGroupMeeting(GroupMeeting groupMeeting)  
  2.         {  
  3.             int rowAffected = 0;  
  4.             using (SqlConnection con = new SqlConnection(strConnectionString))  
  5.             {  
  6.                 SqlCommand command = new SqlCommand("InsertGroupMeeting", con);  
  7.                 command.CommandType = CommandType.StoredProcedure;  
  8.                 command.Parameters.AddWithValue("@ProjectName", groupMeeting.ProjectName);  
  9.                 command.Parameters.AddWithValue("@GroupMeetingLeadName", groupMeeting.GroupMeetingLeadName);  
  10.                 command.Parameters.AddWithValue("@TeamLeadName", groupMeeting.TeamLeadName);  
  11.                 command.Parameters.AddWithValue("@Description", groupMeeting.Description);  
  12.                 command.Parameters.AddWithValue("@GroupMeetingDate", groupMeeting.GroupMeetingDate);  
  13.   
  14.                 if (con.State == ConnectionState.Closed)  
  15.                     con.Open();  
  16.   
  17.                 rowAffected = command.ExecuteNonQuery();  
  18.             }  
  19.             return rowAffected;  
  20.         }  
Code to update the group meeting using ADO.NET is below.
  1. public static int UpdateGroupMeeting(GroupMeeting groupMeeting)  
  2.         {  
  3.             int rowAffected = 0;  
  4.             using (SqlConnection con = new SqlConnection(strConnectionString))  
  5.             {  
  6.                 SqlCommand command = new SqlCommand("UpdateGroupMeeting", con);  
  7.                 command.CommandType = CommandType.StoredProcedure;  
  8.                 command.Parameters.AddWithValue("@Id", groupMeeting.GroupMeetingId);  
  9.                 command.Parameters.AddWithValue("@ProjectName", groupMeeting.ProjectName);  
  10.                 command.Parameters.AddWithValue("@GroupMeetingLeadName", groupMeeting.GroupMeetingLeadName);  
  11.                 command.Parameters.AddWithValue("@TeamLeadName", groupMeeting.TeamLeadName);  
  12.                 command.Parameters.AddWithValue("@Description", groupMeeting.Description);  
  13.                 command.Parameters.AddWithValue("@GroupMeetingDate", groupMeeting.GroupMeetingDate);  
  14.   
  15.                 if (con.State == ConnectionState.Closed)  
  16.                     con.Open();  
  17.   
  18.                 rowAffected = command.ExecuteNonQuery();  
  19.             }  
  20.             return rowAffected;  
  21.         }  

Code to delete the group meeting using ADO.NET is below.

  1. public static int DeleteGroupMeeting(int id)  
  2.         {  
  3.             int rowAffected = 0;  
  4.             using (SqlConnection con = new SqlConnection(strConnectionString))  
  5.             {  
  6.                 SqlCommand command = new SqlCommand("DeleteGroupMeeting", con);  
  7.                 command.CommandType = CommandType.StoredProcedure;  
  8.                 command.Parameters.AddWithValue("@Id", id);                 
  9.   
  10.                 if (con.State == ConnectionState.Closed)  
  11.                     con.Open();  
  12.   
  13.                 rowAffected = command.ExecuteNonQuery();  
  14.             }  
  15.             return rowAffected;  
  16.         }  
As of now, we have completed the model related changes Get, Insert, Update, Delete as shown in the above code. After that, we will create a new controller and Razor Views.

Step 11

Right click on Controller folder => Click on “Add” => Click on Controller.

ASP.NET Core 

Step 12

Select "MVC Controller - Empty" and click on the "Add" button.

ASP.NET Core

 

Provide a meaningful name like “GroupMeeting” as follow.

ASP.NET Core 
Step 13

After adding the controller, you need to import the required namespace. Then add the following code to get all group meeting details and pass to the view as follows. 
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using GroupMeetingASP.NETCoreWebApp.Models;  
  6.   
  7. namespace GroupMeetingASP.NETCoreWebApp.Controllers  
  8. {  
  9.     public class GroupMeetingController : Controller  
  10.     {  
  11.         public IActionResult Index()  
  12.         {  
  13.             return View(GroupMeeting.GetGroupMeetings());  
  14.         }  
  15. }  
  16. }  

Step 14

Right click on ActionResult and click on Add Razor View.

ASP.NET Core 

Step 15

Write code for displaying group meeting data on Index.cshtml view as below.
  1. @model IEnumerable<GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting>  
  2. @{  
  3.     ViewData["Title"] = "Index";  
  4. }  
  5.   
  6. <h4>Group Meeting Web App</h4><hr />  
  7. <h4>  
  8.     <a asp-action="AddGroupMeeting">Add GroupMeeting</a>  
  9. </h4>  
  10. <div>  
  11.     <table class="table table-responsive table-bordered panel-primary">  
  12.         <thead>  
  13.             <th>Project Name</th>  
  14.             <th>Group Lead Name</th>  
  15.             <th>Team Lead Name</th>  
  16.             <th>Description</th>  
  17.             <th>Meeting Date</th>  
  18.         <th></th>  
  19.         </thead>  
  20.         <tbody>  
  21.             @foreach (var item in Model)  
  22.             {   
  23.             <tr>  
  24.                 <td>@Html.DisplayFor(model => item.ProjectName)</td>  
  25.                 <td>@Html.DisplayFor(model => item.GroupMeetingLeadName)</td>  
  26.                 <td>@Html.DisplayFor(model => item.TeamLeadName)</td>  
  27.                 <td>@Html.DisplayFor(model => item.Description)</td>  
  28.                 <td>@Html.DisplayFor(model => item.GroupMeetingDate)</td>  
  29.                 <td>  
  30.                     <a asp-action="EditMeeting" asp-route-id="@item.GroupMeetingId">Edit</a>|  
  31.                     <a asp-action="DeleteMeeting" asp-route-id="@item.GroupMeetingId">Delete</a>  
  32.                 </td>  
  33.             </tr>  
  34.   
  35.             }  
  36.         </tbody>  
  37.     </table>  
  38. </div>  
 Click on Startup.cs file and change the Controller name as "GroupMeeting" controller.
  1. app.UseMvc(routes =>  
  2.            {  
  3.                routes.MapRoute(  
  4.                    name: "default",  
  5.                    template: "{controller=GroupMeeting}/{action=Index}/{id?}");  
  6.            });  
 After changing the controller name in startup.cs file, click on IIS Express to run the application OR press F5.
 
ASP.NET Core 
 
Index page displays as below.
 
ASP.NET Core
 Step 16

We will create “AddGroupMeeting” view in the GroupMeeting controller And write the following code. We have written two views - first is "HttpGet" and the second one is "HttpPost".

  1. [HttpGet]  
  2.         public IActionResult AddGroupMeeting()  
  3.         {  
  4.             return View();  
  5.         }  
  6.         [HttpPost]  
  7.         public IActionResult AddGroupMeeting([Bind] GroupMeeting groupMeeting)  
  8.         {  
  9.             if (ModelState.IsValid)  
  10.             {  
  11.                 if (GroupMeeting.AddGroupMeeting(groupMeeting) > 0)  
  12.                 {  
  13.                     return RedirectToAction("Index");  
  14.                 }  
  15.             }  
  16.             return View(groupMeeting);  
  17.         }  
Step 16

We will create “AddGroupMeeting.cshtml” View and write the code to add the group meeting detail.
  1. @model GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting  
  2. @{  
  3.     ViewData["Title"] = "AddGroupMeeting";  
  4. }  
  5.   
  6. <h2>Add Group Meeting</h2>  
  7. <div class="row">  
  8.     <div class="col-md-4">  
  9.         <form asp-action="AddGroupMeeting">  
  10.             <div class="">  
  11.                 <label asp-for="ProjectName" class="control-label"></label>  
  12.                 <input asp-for="ProjectName" class="form-control" />  
  13.                 <span class="alert-danger" asp-validation-for="ProjectName"></span>  
  14.             </div>  
  15.             <div class="form-group">  
  16.                 <label asp-for="GroupMeetingLeadName" class="control-label"></label>  
  17.                 <input asp-for="GroupMeetingLeadName" class="form-control" />  
  18.                 <span class="alert-danger" asp-validation-for="GroupMeetingLeadName"></span>  
  19.             </div>  
  20.             <div class="form-group">  
  21.                 <label asp-for="TeamLeadName" class="control-label"></label>  
  22.                 <input asp-for="TeamLeadName" class="form-control" />  
  23.                 <span class="alert-danger" asp-validation-for="TeamLeadName"></span>  
  24.             </div>  
  25.             <div class="form-group">  
  26.                 <label asp-for="Description" class="control-label"></label>  
  27.                 <input asp-for="Description" class="form-control" />  
  28.                 <span class="alert-danger" asp-validation-for="Description"></span>  
  29.             </div>  
  30.             <div class="form-group">  
  31.                 <label asp-for="GroupMeetingDate" class="control-label"></label>  
  32.                 <input asp-for="GroupMeetingDate" class="form-control" />  
  33.                 <span class="alert-danger" asp-validation-for="GroupMeetingDate"></span>  
  34.             </div>  
  35.             <div class="form-group">  
  36.                 <input type="submit" value="Create Meeting" class="btn btn-success btn-sm" />  
  37.             </div>             
  38.         </form>  
  39.     </div>  
  40.     <div class="col-md-8">  
  41.   
  42.     </div>  
  43. </div>  
  44. <div>  
  45.     <a asp-action="Index">Back To Home</a>  
  46. </div>  
"AddGroupMeeting" view displayed as below.

ASP.NET Core
 
We have also added the validation using DataAnnotations on add group meeting page.
 
ASP.NET Core 
 
Enter the valid information in the group meeting page and click on “Create Meeting” button. Then it will redirect to the index view page.

Step 17

We will create “EditMeeting” view in the GroupMeeting Controller and write the code to edit the group meeting detail as follow. There are two views of EditMeeting "HttpGet" and "HttpPost". The "HttpGet" edit meeting view having id as a parameter gets called when clicking on "Edit" button on index view page. 

  1. [HttpGet]  
  2.         public IActionResult EditMeeting(int? id)  
  3.         {  
  4.             if (id == null)  
  5.             {  
  6.                 return NotFound();  
  7.             }  
  8.             GroupMeeting group = GroupMeeting.GetGroupMeetingById(id);  
  9.             if (group == null)  
  10.                 return NotFound();  
  11.             return View(group);  
  12.         }  
  13.   
  14.         [HttpPost]  
  15.         public IActionResult EditMeeting(int id, [Bind] GroupMeeting groupMeeting)  
  16.         {  
  17.             if (id != groupMeeting.GroupMeetingId)  
  18.                 return NotFound();  
  19.   
  20.             if (ModelState.IsValid)  
  21.             {  
  22.                 GroupMeeting.UpdateGroupMeeting(groupMeeting);  
  23.                 return RedirectToAction("Index");  
  24.             }  
  25.             return View(groupMeeting);  
  26.         }  
Click on "Edit" button on index view page as follows:
 
ASP.NET Core

It will open the following page when you click on "edit" button. Then the group meeting will get updated into the database and redirected to the index view page.

 

ASP.NET Core

 

Step 18

We will create “DeleteMeeting” view in the GroupMeeting Controller and write the code to edit the group meeting detail as follows.
  1. [HttpGet]  
  2.        public IActionResult DeleteMeeting(int id)  
  3.        {  
  4.            GroupMeeting group = GroupMeeting.GetGroupMeetingById(id);  
  5.            if (group==null)  
  6.            {  
  7.                return NotFound();  
  8.            }  
  9.   
  10.            return View(group);  
  11.        }  
  12.        [HttpPost]  
  13.        public IActionResult DeleteMeeting(int id,GroupMeeting groupMeeting)  
  14.        {  
  15.            if (GroupMeeting.DeleteGroupMeeting(id) > 0)  
  16.            {  
  17.                return RedirectToAction("Index");  
  18.            }  
  19.            return View(groupMeeting);  
  20.        }  
Step 18

Write the “DeleteMeeting.cshtml” view page code as follow.
  1. @model GroupMeetingASP.NETCoreWebApp.Models.GroupMeeting  
  2. @{  
  3.     ViewData["Title"] = "DeleteMeeting";  
  4. }  
  5.   
  6. <h3 class="alert">Are you sure you want to delete this?</h3>  
  7. <div>  
  8.     <dl class="dl-horizontal">  
  9.         <dt>  
  10.             @Html.DisplayNameFor(model => model.ProjectName)  
  11.         </dt>  
  12.         <dd>  
  13.             @Html.DisplayFor(model => model.ProjectName)  
  14.         </dd>  
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.GroupMeetingLeadName)  
  17.         </dt>  
  18.         <dd>  
  19.             @Html.DisplayFor(model => model.GroupMeetingLeadName)  
  20.         </dd>  
  21.         <dt>  
  22.             @Html.DisplayNameFor(model => model.TeamLeadName)  
  23.         </dt>  
  24.         <dd>  
  25.             @Html.DisplayFor(model => model.TeamLeadName)  
  26.         </dd>  
  27.         <dt>  
  28.             @Html.DisplayNameFor(model => model.Description)  
  29.         </dt>  
  30.         <dd>  
  31.             @Html.DisplayFor(model => model.Description)  
  32.         </dd>  
  33.         <dt>  
  34.             @Html.DisplayNameFor(model => model.GroupMeetingDate)  
  35.         </dt>  
  36.         <dd>  
  37.             @Html.DisplayFor(model => model.GroupMeetingDate)  
  38.         </dd>  
  39.     </dl>  
  40.   
  41.     <form asp-action="DeleteMeeting">  
  42.         <input type="hidden" asp-for="GroupMeetingId" />  
  43.         <input type="submit" value="YES" class="btn btn-danger btn-sm" /> <a asp-action="Index" class="btn btn-danger">NO</a>  
  44.     </form>  
  45. </div>    

Run the appliation and the defualt index view page will open. Then click on delete link as follows.

 

ASP.NET Core

 

After clicking on “delete” button on the index view page, the following page will open for confirmation to delete the group meeting.

ASP.NET Core
After that click on “Yes” button, the selected group meeting will get deleted from the list of group meetings and the page will redirect to the index view page and the page will look as follows.

ASP.NET Core

I hope you understand the basic concepts of CRUD operations using ASP.NET Core 2.0 with Razor view pages using ADO.NET.