You are on page 1of 13

AngularJS CRUD Operation using ASP.

NET MVC
I am a .NET Developer and I’m new in AngularJS. I started using AngularJS in about a week
ago and I decided to create a full AngularJS CRUD Operation using ASP.NET MVC. This article
will show you how I created a project with CRUD functionality using AngularJS.
For an overview of AngularJS, you can visit AngularJS introduction from this
site https://docs.angularjs.org/guide/introduction.

To start, below are the summary of the steps I have done to fully implement AngularJS
CRUD project.

AngularJS CRUD Operation using ASP.NET


 Create SQL Database
 Create CRUD Stored Procedure
 Start a New ASP.NET MVC project
 Create a separate Class for CRUD functions
 Create CRUD Action Result in main controller( HomeController)
 Design a View (Front End Design) with AngularJS App
To make this article much easier I copied all the code I have used in every associated class
file in the steps above.

Let’s Start:

1. Create SQL Database:


To execute CRUD operation we need to have data storage. I assume you have already used
SQL Database. Create a database and a table. In my case, I created a database
named EmployeeDB and a table named EmployeeRecord. Image below.

2. Create CRUD Stored Procedure


If this is your first time using a SQL stored procedure you can refer to my previous
article How to create a stored procedure. Below are the Stored Procedures and the
associated code I used.

Code:

DeleteEmployee Procedure
1 USE [EmployeeDB]
2 GO
3 /****** Object: StoredProcedure [dbo].[DeleteEmployee] Script Date: 20/06/2018 9:22:38 PM ******/
4 SET ANSI_NULLS ON
5 GO
6 SET QUOTED_IDENTIFIER ON
7 GO
8
9 ALTER PROCEDURE [dbo].[DeleteEmployee]
10 @ID int
11 AS
12 BEGIN
13 SET NOCOUNT ON;
14 Delete From EmployeeRecord WHERE ID = @ID
15 END

SQL Stored Procedure – InsertEmployee

1 USE [EmployeeDB]
2 GO
3 /****** Object: StoredProcedure [dbo].[InsertEmployee] Script Date: 20/06/2018 9:22:57 PM ******/
4 SET ANSI_NULLS ON
5 GO
6 SET QUOTED_IDENTIFIER ON
7 GO
8
9 ALTER PROCEDURE [dbo].[InsertEmployee]
10 @Name nvarchar(50),
11 @Email nvarchar(50)
12 AS
13 BEGIN
14 SET NOCOUNT ON;
15 INSERT INTO EmployeeRecord VALUES(@Name, @Email)
16 END

SelectEmployee Procedure

1 USE [EmployeeDB]
2 GO
3 /****** Object: StoredProcedure [dbo].[SelectEmployee] Script Date: 20/06/2018 9:23:00 PM ******/
4 SET ANSI_NULLS ON
5 GO
6 SET QUOTED_IDENTIFIER ON
7 GO
8
9 ALTER PROCEDURE [dbo].[SelectEmployee]
10
11 AS
12 BEGIN
13
14 SET NOCOUNT ON;
15 Select * FROm EmployeeRecord
16 END

UpdateEmployee Procedure

1 USE [EmployeeDB]
2 GO
3 /****** Object: StoredProcedure [dbo].[UpdateEmployee] Script Date: 20/06/2018 9:23:04 PM ******/
4 SET ANSI_NULLS ON
5 GO
6 SET QUOTED_IDENTIFIER ON
7 GO
8
9 ALTER PROCEDURE [dbo].[UpdateEmployee]
10 @ID int ,
11 @Name nvarchar(50),
12 @Email nvarchar(50)
13 AS
14 BEGIN
15 SET NOCOUNT ON;
16 Update EmployeeRecord set Name = @Name , Email = @Email WHERE ID = @ID
17 END

3. Start a New ASP.NET MVC project


Now, that we have already prepared our backend, which is the SQL Database and stored
procedures. We can now start creating our project. Open your Visual Studio and create a
new ASP.NET Web Application using MVC template. If you have no idea how to start a
project you can visit my previous article on how to start in ASP.NET MVC.

4. Create a separate Class for CRUD functions


To organize our code I suggest we create a separate class containing all the connection we
need to established connectivity to our SQL Stored Procedures.
But first, let’s create a folder inside our solution explorer by simply right-clicking on the
project name and selecting Add > New Folder. See image below
Inside that folder create a Class. Add Class by simply right-clicking your project name and
select Add > Class. Below are the folder and class I created.

As you can see from the image above I named my folder as CRUD_function and my class
as CRUD. Now, let’s start adding code. Open CRUD.cs and copy the code snippet below. This
is where we put all our connection to the SQL Stored procedures.
Note: To view your connection string you can refer to my previous article Manual viewing
SQL Connection String.

CRUD.cs – Code:

1 using AngularJS_CRUD.Models;
2 using System;
3 using System.Collections.Generic;
4 using System.Data;
5 using System.Data.SqlClient;
6 using System.Linq;
7 using System.Web;
8
9 namespace AngularJS_CRUD.Crud_Function
10 {
11 public class CRUD
12 {
13 string connectionString = "Data Source=LAPTOP-JD2CG4N8;Initial Catalog=EmployeeDB;Integrated
14 Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
15 public List<EmployeeModel> GetEmployees()
16 {
17 List<EmployeeModel> list = new List<EmployeeModel>();
18 using (SqlConnection conn = new SqlConnection(connectionString))
19 {
20 SqlCommand cmd = new SqlCommand("dbo.SelectEmployee", conn);
21 cmd.CommandType = System.Data.CommandType.StoredProcedure;
22 SqlDataAdapter da = new SqlDataAdapter(cmd);
23 DataSet ds = new DataSet();
24 da.Fill(ds);
25 if (ds.Tables.Count > 0)
26 {
27 if (ds.Tables[0].Rows.Count > 0)
28 {
29 foreach (DataRow row in ds.Tables[0].Rows)
30 {
31 list.Add(new EmployeeModel
32 {
33 Name = row["Name"].ToString().Trim(),
34 Email = row["Email"].ToString().Trim(),
35 ID = int.Parse(row["ID"].ToString())
36
37 });
38 }
39 }
40 }
41
42 }
43 return list;
44 }
45 public string AddEmployee(EmployeeModel empDetails)
46 {
47 string response = "";
48 using (SqlConnection conn = new SqlConnection(connectionString))
49 {
50 SqlCommand cmd = new SqlCommand("InsertEmployee", conn);
51 cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = empDetails.Name;
52 cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = empDetails.Email;
53 cmd.CommandType = CommandType.StoredProcedure;
54
55 conn.Open();
56 cmd.ExecuteNonQuery();
57 response = "Success";
58 conn.Close();
59 }
60 return response;
61 }
62
63 public string updateEmployee(EmployeeModel empdetails)
64 {
65 string response = "";
66 using (SqlConnection conn = new SqlConnection(connectionString))
67 {
68 SqlCommand cmd = new SqlCommand("UpdateEmployee", conn);
69 cmd.Parameters.Add("@ID", SqlDbType.Int).Value = empdetails.ID;
70 cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = empdetails.Name;
71 cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = empdetails.Email;
72 cmd.CommandType = CommandType.StoredProcedure;
73
74 conn.Open();
75 cmd.ExecuteNonQuery();
76 response = "Success";
77 conn.Close();
78 }
79 return response;
80 }
81 public string deleteEmployee(int id)
82 {
83 string response = "";
84 using (SqlConnection conn = new SqlConnection(connectionString))
85 {
86 SqlCommand cmd = new SqlCommand("DeleteEmployee", conn);
87 cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id;
88 cmd.CommandType = CommandType.StoredProcedure;
89
90 conn.Open();
91 cmd.ExecuteNonQuery();
92 response = "Success";
93 conn.Close();
94 }
95 return response;
96 }
97 }
}

5. Create CRUD Action Result in main controller( HomeController)


In this step, we will create an Action Result method in our main controller. If you are using
the default MVC template, your default controller is HomeController. Located inside the
folder Controller. Open HomeController. Copy the code snippet below.

HomeController.cs – Codes:

1 using AngularJS_CRUD.Crud_Function;
2 using AngularJS_CRUD.Models;
3 using Newtonsoft.Json;
4 using System;
5 using System.Collections.Generic;
6 using System.Linq;
7 using System.Web;
8 using System.Web.Mvc;
9
10 namespace AngularJS_CRUD.Controllers
11 {
12 public class HomeController : Controller
13 {
14 CRUD service = new CRUD();
15
16 public ActionResult Index()
17 {
18 return View();
19 }
20
21 [HttpGet]
22 public ActionResult getEmployee()
23 {
24 List<EmployeeModel> list = new List<EmployeeModel>();
25
26 list = service.GetEmployees();
27
28 string json_data = JsonConvert.SerializeObject(list);
29
30 return Json(json_data, JsonRequestBehavior.AllowGet);
31 }
32 [HttpPost]
33 public ActionResult AddEmployee(EmployeeModel empdetails)
34 {
35 string result = service.AddEmployee(empdetails);
36
37 List<EmployeeModel> list = new List<EmployeeModel>();
38 list = service.GetEmployees();
39
40 string json_data = JsonConvert.SerializeObject(list);
41
42 return Json(json_data, JsonRequestBehavior.AllowGet);
43 }
44
45 [HttpPost]
46 public ActionResult UpdateEmployee(EmployeeModel empdetails)
47 {
48 string result = service.updateEmployee(empdetails);
49
50 List<EmployeeModel> list = new List<EmployeeModel>();
51 list = service.GetEmployees();
52
53 string json_data = JsonConvert.SerializeObject(list);
54
55 return Json(json_data, JsonRequestBehavior.AllowGet);
56 }
57 [HttpPost]
58 public ActionResult DeleteEmployee(int ID)
59 {
60 string result = service.deleteEmployee(ID);
61
62 List<EmployeeModel> list = new List<EmployeeModel>();
63 list = service.GetEmployees();
64
65 string json_data = JsonConvert.SerializeObject(list);
66
67 return Json(json_data, JsonRequestBehavior.AllowGet);
68 }
69 }
70 }

6. Design a View (Front End Design) with AngularJS App


After we have fully created all the necessary CRUD functions that we need, let’s start
creating our front-end design with AngularJS framework. Navigate to your default view
which is located inside the folder Views > Home > index.cshtml .Open index.cshtml and
replace the code with the snippet below.

Project Preview:
Add of employee preview

Index.cshtml – Code:

Note: with AngularJS Script

1 @using AngularJS_CRUD.Models
2 @model EmployeeModel
3 @{
4 ViewBag.Title = "Home Page";
5 }
6
7 <script src="~/Scripts/Angular.min.js"></script>
8 <div ng-app="HomeApp" ng-controller="HomeController">
9
10 <hr />
11 <div class="header-info">
12 <label class="">Employee Details</label>
13 <button class="btn btn-default pull-right" data-toggle="modal" data-target="#AddModal" ng-
14 click="clearModel()">Add Employee</button>
15 </div>
16 <hr />
17 <br />
18 <div class="alert alert-info" ng-if="message">
19 <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
20 {{message}}
21 </div>
22 <div class="table-data">
23 <table class="table table-bordered table-responsive table-hover">
24 <thead>
25 <tr>
26 <th>ID</th>
27 <th>Full Name</th>
28 <th>Email Address</th>
29 <th>Edit</th>
30 <th>Delete</th>
31 </tr>
32 </thead>
33 <tbody>
34 <tr ng-repeat="names in employee">
35 <td>{{ names.ID }}</td>
36 <td>{{ names.Name }}</td>
37 <td>{{ names.Email }}</td>
38 <td><button class="btn btn-info" data-toggle="modal" data-target="#EditModal" ng-
39 click="selectUser(names)">Edit</button></td>
40 <td><button class="btn btn-danger" ng-click="DeleteEmployee(names)">Delete</button></td>
41 </tr>
42 </tbody>
43 </table>
44
45 </div>
46
47 <!-- Modal Add modal-->
48 <div class="modal fade" id="AddModal" role="dialog">
49 <div class="modal-dialog">
50
51 <!-- Modal content-->
52 <div class="modal-content">
53 <form name="employee_form" data-ng-submit="AddEmployee()">
54 <div class="modal-header">
55 <button type="button" class="close" data-dismiss="modal">&times;</button>
56 <h4 class="modal-title">Add Employee Details</h4>
57 </div>
58 <div class="modal-body">
59 <div class="form-group">
60 <label for="exampleInputEmail1">User Name</label>
61 <input type="text" class="form-control" id="fullname" aria-describedby="emailHelp"
62 placeholder="Enter Full Name" ng-model="model.Name" required="required">
63 </div>
64 <div class="form-group">
65 <label for="exampleInputEmail1">Email address</label>
66 <input type="email" class="form-control" id="exampleInputEmail1" aria-
67 describedby="emailHelp" placeholder="Enter email" ng-model="model.Email" required="required">
68 <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
69 else.</small>
70 </div>
71 </div>
72
73 <div class="modal-footer">
74 <button type="submit" class="btn btn-default pull-left">Save</button>
75 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
76 </div>
77 </form>
78 </div>
79
80 </div>
81 </div>
82
83 <!-- Edit modal-->
84 <div class="modal fade" id="EditModal" role="dialog">
85 <div class="modal-dialog">
86
87 <!-- Modal content-->
88 <div class="modal-content">
89 <form name="employee_form" data-ng-submit="UpdateEmployee()">
90 <div class="modal-header">
91 <button type="button" class="close" data-dismiss="modal">&times;</button>
92 <h4 class="modal-title">Edit Employee Details</h4>
93 </div>
94 <div class="modal-body">
95 <div class="form-group">
96 <label for="exampleInputEmail1">User Name</label>
97 <input type="text" class="form-control" id="fullname" aria-describedby="emailHelp"
98 placeholder="Enter FullName" ng-model="selectedUser.Name" required="required">
99 </div>
100 <div class="form-group">
101 <label for="exampleInputEmail1">Email address</label>
102 <input type="email" class="form-control" id="exampleInputEmail1" aria-
103 describedby="emailHelp" placeholder="Enter email" ng-model="selectedUser.Email" required="required">
104 <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
105 else.</small>
106 </div>
107
108 </div>
109
110 <div class="modal-footer">
111 <button type="submit" class="btn btn-default pull-left">Save</button>
112 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
113 </div>
114 </form>
115 </div>
116
117 </div>
118 </div>
119 </div>
120
121
122 <script>
123
124 var app = angular.module('HomeApp', []);
125 app.controller('HomeController', function ($scope, $http) {
126
127 $scope.model = @Html.Raw(Json.Encode(Model))
128
129 $http({
130 method: 'GET',
131 url: '@Url.Action("getEmployee", "Home")',
132 headers: {
133 'Content-type': 'application/json'
134 }
135 }).then(function (response) {
136 debugger;
137 $scope.employee = JSON.parse(response.data);
138 }, function (error) {
139 console.log(error);
140 });
141
142
143
144 $scope.AddEmployee = function () {
145 debugger;
146 var eee = $scope.model;
147 $http({
148 method: 'POST',
149 url: '@Url.Action("AddEmployee", "Home")',
150 data: $scope.model,
151 headers: {
152 'Content-type': 'application/json'
153 }
154 }).then(function (response) {
155 $scope.employee = JSON.parse(response.data);
156 $scope.message = "Employee added Successfully";
157
158 $("#AddModal").modal("hide");
159 }, function (error) {
160 console.log(error);
161 });
162 }
163
164 $scope.selectUser = function (names) {
165 $scope.selectedUser = names;
166 }
167
168 $scope.UpdateEmployee = function () {
169 var eee = $scope.selectedUser;
170 $http({
171 method: 'POST',
172 url: '@Url.Action("UpdateEmployee", "Home")',
173 data: $scope.selectedUser,
174 headers: {
175 'Content-type': 'application/json'
176 }
177 }).then(function (response) {
178 $scope.employee = JSON.parse(response.data);
179 $scope.message = "Employee updated Successfully";
180 $("#EditModal").modal("hide");
181 }, function (error) {
182 console.log(error);
183 });
184 }
185
186 $scope.DeleteEmployee = function (names) {
187
188 $http({
189 method: 'POST',
190 url: '@Url.Action("DeleteEmployee", "Home")',
191 data: names,
192 headers: {
193 'Content-type': 'application/json'
194 }
195 }).then(function (response) {
196 $scope.employee = JSON.parse(response.data);
197 $scope.message = "Employee Deleted Successfully";
198 $("#EditModal").modal("hide");
199 }, function (error) {
200 console.log(error);
201 });
}
$scope.clearModel = function () {
$scope.model = null;

});
</script>

And we are done. Run your project and see if it works. You can comment below for technical
questions about this article.
Thank you for reading!!