AngularJS CRUD Operation Using ASP.NET MVC

Let’s start this article.

First, we create an MVC project. Go to File-> New-> Project and select “ASP.NET Web Application”.

New

Now, select MVC template for the project.

MVC

In Solution Explorer window, we can see the structure of our project.

Solution Explorer

Now, we add the model classes in our project. We have an Employee table which we will use in our project and implement the CRUD operation on.

  1. CREATE TABLE [dbo].[Employee](  
  2. [Emp_Id] [int] IDENTITY(1,1) NOT NULL,  
  3. [Emp_Name] [varchar](maxNULL,  
  4. [Emp_City] [varchar](maxNULL,  
  5. [Emp_Age] [intNULL,  
  6. CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  7. (  
  8. [Emp_Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  11.   
  12. GO  
table

For database CRUD operation, we will use the Entity Framework Data First approach. For this, right click on “Model” folder and click on “New Item” option.

New Item

Now, select “ADO.NET Entity Data Model” and name it as “EmployeeModel”.

ADO.NET Entity Data Model

ADO.NET Entity Data Model

Establish a connection with “SQL Server Database” Engine.

connection

Select Employee table Entity Data Model Wizard and click on Finish button.

table

Now, go to your project’s Model folder where you can see that Employee Model class has been created. So, you have successfully created a connection with database.

Model

After this, we download and install the AngularJS package. Right click on Project Name and select “Manage NuGet Packages” option and download the AngularJS packages.

Manage Nuget Packages

In Scripts folder, you can find that AngularJS files have been installed successfully.

Folder

Now, we create the Employee Controller. So, right click on Controller Folder and create an empty Controller.

create

Now, copy and paste the following code into your Employee Controller section.
  1. using AngularCRUD.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AngularCRUD.Controllers {  
  8.     public class EmployeeController: Controller {  
  9.         // GET: Employee  
  10.         public ActionResult Index() {  
  11.                 return View();  
  12.             }  
  13.             /// <summary>  
  14.             ///   
  15.             /// Get All Employee  
  16.             /// </summary>  
  17.             /// <returns></returns>  
  18.         public JsonResult Get_AllEmployee() {  
  19.                 using(DemoEntities Obj = new DemoEntities()) {  
  20.                     List < Employee > Emp = Obj.Employees.ToList();  
  21.                     return Json(Emp, JsonRequestBehavior.AllowGet);  
  22.                 }  
  23.             }  
  24.             /// <summary>  
  25.             /// Get Employee With Id  
  26.             /// </summary>  
  27.             /// <param name="Id"></param>  
  28.             /// <returns></returns>  
  29.         public JsonResult Get_EmployeeById(string Id) {  
  30.                 using(DemoEntities Obj = new DemoEntities()) {  
  31.                     int EmpId = int.Parse(Id);  
  32.                     return Json(Obj.Employees.Find(EmpId), JsonRequestBehavior.AllowGet);  
  33.                 }  
  34.             }  
  35.             /// <summary>  
  36.             /// Insert New Employee  
  37.             /// </summary>  
  38.             /// <param name="Employe"></param>  
  39.             /// <returns></returns>  
  40.         public string Insert_Employee(Employee Employe) {  
  41.                 if (Employe != null) {  
  42.                     using(DemoEntities Obj = new DemoEntities()) {  
  43.                         Obj.Employees.Add(Employe);  
  44.                         Obj.SaveChanges();  
  45.                         return "Employee Added Successfully";  
  46.                     }  
  47.                 } else {  
  48.                     return "Employee Not Inserted! Try Again";  
  49.                 }  
  50.             }  
  51.             /// <summary>  
  52.             /// Delete Employee Information  
  53.             /// </summary>  
  54.             /// <param name="Emp"></param>  
  55.             /// <returns></returns>  
  56.         public string Delete_Employee(Employee Emp) {  
  57.                 if (Emp != null) {  
  58.                     using(DemoEntities Obj = new DemoEntities()) {  
  59.                         var Emp_ = Obj.Entry(Emp);  
  60.                         if (Emp_.State == System.Data.Entity.EntityState.Detached) {  
  61.                             Obj.Employees.Attach(Emp);  
  62.                             Obj.Employees.Remove(Emp);  
  63.                         }  
  64.                         Obj.SaveChanges();  
  65.                         return "Employee Deleted Successfully";  
  66.                     }  
  67.                 } else {  
  68.                     return "Employee Not Deleted! Try Again";  
  69.                 }  
  70.             }  
  71.             /// <summary>  
  72.             /// Update Employee Information  
  73.             /// </summary>  
  74.             /// <param name="Emp"></param>  
  75.             /// <returns></returns>  
  76.         public string Update_Employee(Employee Emp) {  
  77.             if (Emp != null) {  
  78.                 using(DemoEntities Obj = new DemoEntities()) {  
  79.                     var Emp_ = Obj.Entry(Emp);  
  80.                     Employee EmpObj = Obj.Employees.Where(x => x.Emp_Id == Emp.Emp_Id).FirstOrDefault();  
  81.                     EmpObj.Emp_Age = Emp.Emp_Age;  
  82.                     EmpObj.Emp_City = Emp.Emp_City;  
  83.                     EmpObj.Emp_Name = Emp.Emp_Name;  
  84.                     Obj.SaveChanges();  
  85.                     return "Employee Updated Successfully";  
  86.                 }  
  87.             } else {  
  88.                 return "Employee Not Updated! Try Again";  
  89.             }  
  90.         }  
  91.     }  
  92. }  
After creating the Controller, now, we create a View. Right click on Index method and create an Empty View.

empty view.

Paste the following code into the Index View:
  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <style>  
  6. .btn-space {  
  7. margin-left: -5%;  
  8. background-color: cornflowerblue;  
  9. font-size: large;  
  10. }  
  11. </style>  
  12. <h2>Index</h2>  
  13. <div ng-app="myApp">  
  14.     <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">  
  15.         <p class="divHead">List of Employee</p>  
  16.         <table cellpadding="12" class="table table-bordered table-hover">  
  17.             <tr>  
  18.                 <td>  
  19.                     <b>ID</b>  
  20.                 </td>  
  21.                 <td>  
  22.                     <b>Name</b>  
  23.                 </td>  
  24.                 <td>  
  25.                     <b>City</b>  
  26.                 </td>  
  27.                 <td>  
  28.                     <b>Age</b>  
  29.                 </td>  
  30.                 <td>  
  31.                     <b>Actions</b>  
  32.                 </td>  
  33.             </tr>  
  34.             <tr ng-repeat="Emp in employees">  
  35.                 <td>  
  36. {{Emp.Emp_Id}}  
  37. </td>  
  38.                 <td>  
  39. {{Emp.Emp_Name}}  
  40. </td>  
  41.                 <td>  
  42. {{Emp.Emp_City}}  
  43. </td>  
  44.                 <td>  
  45. {{Emp.Emp_Age}}  
  46. </td>  
  47.                 <td>  
  48.                     <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />  
  49.                     <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />  
  50.                 </td>  
  51.             </tr>  
  52.         </table>  
  53.         <div class="form-horizontal" role="form">  
  54.             <div class="container">  
  55.                 <div class="row">  
  56.                     <h2>  
  57.                         <span id="spn">Add New Employee</span>  
  58.                     </h2>  
  59.                 </div>  
  60.                 <div class="row">  
  61.                     <div class="col-sm-6 col-lg-4">  
  62.                         <div class="form-group">  
  63.                             <label class="col-md-4 control-label">Name:</label>  
  64.                             <div class="col-md-8">  
  65.                                 <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName">  
  66.                                 </div>  
  67.                             </div>  
  68.                         </div>  
  69.                         <div class="col-sm-6 col-lg-4">  
  70.                             <div class="form-group">  
  71.                                 <label class="col-md-4 control-label">City:</label>  
  72.                                 <div class="col-md-8">  
  73.                                     <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">  
  74.                                     </div>  
  75.                                 </div>  
  76.                             </div>  
  77.                             <div class="col-sm-6 col-lg-4">  
  78.                                 <div class="form-group">  
  79.                                     <label class="col-md-4 control-label">Age:</label>  
  80.                                     <div class="col-md-8">  
  81.                                         <input type="text" class="form-control" id="inputLabel3" placeholder="Age" ng-model="EmpAge">  
  82.                                         </div>  
  83.                                     </div>  
  84.                                 </div>  
  85.                             </div>  
  86.                             <div class="row">  
  87.                                 <div class="col-sm-6 col-lg-4">  
  88.                                     <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />  
  89.                                 </div>  
  90.                             </div>  
  91.                         </div>  
  92.                     </div>  
  93.                 </div>  
  94. @Html.Hidden("EmpID_")  
  95.   
  96.             </div>  
For CRUD operations in AngularJS, we create a JavaScript file, write the code into that file, and implement this file into our Index View.

First, create a JavaScript file and copy the following code.

create

JavaScript code
  1. var app = angular.module("myApp", []);  
  2. app.controller("myCtrl"function($scope, $http) {  
  3.     debugger;  
  4.     $scope.InsertData = function() {  
  5.         var Action = document.getElementById("btnSave").getAttribute("value");  
  6.         if (Action == "Submit") {  
  7.             $scope.Employe = {};  
  8.             $scope.Employe.Emp_Name = $scope.EmpName;  
  9.             $scope.Employe.Emp_City = $scope.EmpCity;  
  10.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  11.             $http({  
  12.                 method: "post",  
  13.                 url: "http://localhost:39209/Employee/Insert_Employee",  
  14.                 datatype: "json",  
  15.                 data: JSON.stringify($scope.Employe)  
  16.             }).then(function(response) {  
  17.                 alert(response.data);  
  18.                 $scope.GetAllData();  
  19.                 $scope.EmpName = "";  
  20.                 $scope.EmpCity = "";  
  21.                 $scope.EmpAge = "";  
  22.             })  
  23.         } else {  
  24.             $scope.Employe = {};  
  25.             $scope.Employe.Emp_Name = $scope.EmpName;  
  26.             $scope.Employe.Emp_City = $scope.EmpCity;  
  27.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  28.             $scope.Employe.Emp_Id = document.getElementById("EmpID_").value;  
  29.             $http({  
  30.                 method: "post",  
  31.                 url: "http://localhost:39209/Employee/Update_Employee",  
  32.                 datatype: "json",  
  33.                 data: JSON.stringify($scope.Employe)  
  34.             }).then(function(response) {  
  35.                 alert(response.data);  
  36.                 $scope.GetAllData();  
  37.                 $scope.EmpName = "";  
  38.                 $scope.EmpCity = "";  
  39.                 $scope.EmpAge = "";  
  40.                 document.getElementById("btnSave").setAttribute("value""Submit");  
  41.                 document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";  
  42.                 document.getElementById("spn").innerHTML = "Add New Employee";  
  43.             })  
  44.         }  
  45.     }  
  46.     $scope.GetAllData = function() {  
  47.         $http({  
  48.             method: "get",  
  49.             url: "http://localhost:39209/Employee/Get_AllEmployee"  
  50.         }).then(function(response) {  
  51.             $scope.employees = response.data;  
  52.         }, function() {  
  53.             alert("Error Occur");  
  54.         })  
  55.     };  
  56.     $scope.DeleteEmp = function(Emp) {  
  57.         $http({  
  58.             method: "post",  
  59.             url: "http://localhost:39209/Employee/Delete_Employee",  
  60.             datatype: "json",  
  61.             data: JSON.stringify(Emp)  
  62.         }).then(function(response) {  
  63.             alert(response.data);  
  64.             $scope.GetAllData();  
  65.         })  
  66.     };  
  67.     $scope.UpdateEmp = function(Emp) {  
  68.         document.getElementById("EmpID_").value = Emp.Emp_Id;  
  69.         $scope.EmpName = Emp.Emp_Name;  
  70.         $scope.EmpCity = Emp.Emp_City;  
  71.         $scope.EmpAge = Emp.Emp_Age;  
  72.         document.getElementById("btnSave").setAttribute("value""Update");  
  73.         document.getElementById("btnSave").style.backgroundColor = "Yellow";  
  74.         document.getElementById("spn").innerHTML = "Update Employee Information";  
  75.     }  
  76. })  
Now, provide the references of AngularJS and AngularCode file that we created into Index View.

references

Now, I think our project is ready to work. So, let’s run the application. Press F5 and you can see that following screen will be visible on your browser.

browser

Now, we will learn about all CRUD operations (create, read, update and delete) and understand how they work.

Get all Employee Record

When we run the application, at first, all employees records will retrieve and show up in the grid. You can see that in “ng-init” directive, we call the “getAllData” record. This method is responsible for retrieval of all the records.

code

In “AngularCode” file you can find this method.
code

In “GetAllData” method, we used the $http service of AngularJS and call the “Get_AllEmployee” method of “Employee” controller. Code of “Get_AllEmployee” method is the following.

Code

In this method, we get all employees' records from “Employee” entity and pass as JSON result.

Add New Employee

Add New Employee

When we click on “Submit” button, the “InsertData” method will be call.

Submit

In this method, we retrieve the data from Name, City, and Age field and insert into “Employe” object . We call the “Insert_Employee” method of Employee Controller and Pass the “Employe” object as parameter.
code
In controller section, we add the “Employe” object into Employee entity.

code

And pass the Confirmation message as confirmation. Now, you can see that the record of “Sandeep” is added successfully.

index

Delete The Employee Record

We are using ng-repeat directive and inserting Employee Name, Age, Id and City information into table. You can see that  we are creating on extra column(“Action”). In this column, we are adding two buttons for “Delete” and “Update” command and on ng-click directive, we are calling “DeleteEmp” method for deleting operation and “UpdateEmp” for update operation. In both methods, we are passing the Object of Employee.

code

In “DeleteEmp” method, we are calling the “Delete_Employee” of controller using “$http”,
code

In “Delete_Employee” method, we are removing the Employee record from “Employee” table.

code

Let’s try to delete the record of “Pardeep” Employee.

delete

delete

Update Employee Record

In Update command, we are calling the “UpdateEmp” method in which we are inserting the information of employee into textboxes and changing the properties of button and span section.
code

Let’s click on Update button for employee “Nitin”.

Update

Now, we change the name and City for this employee.
Update
When we click on “Update” button, then “InsertData” method of AngularCode file we will be called and “else” section will execute because the  value of the button is not equal to “Submit”.
code

In the above code, we are calling the “Update_Employee” method of Controller. In “Update_Employee” method, we update the record for employee and send the confirmation message.
code

You can check that information for employee “Nitin” has been updated.

output
I hope you liked the article. Thanks to read the article. If you have any doubt our query, then leave it in the comment section.

 

Up Next
    Ebook Download
    View all
    Learn
    View all