Angular CRUD Operation Using MVC

In this post, we will learn how to perform a CRUD (Create, Update, Read, Delete) demo with Angular JS. In this post, we will use our CRUD library from the previous post. It's already added in the source code download link. For this example, we are using MVC application. In this post, I have added a SQL script of employee table and its relative stored procedures, like insert, update, get, get all, delete and add CRUD library reference in MVC project. Let's start a step by step tutorial of Angular CRUD demo.

Database

Step 1

Create employee table.

  1. CREATE TABLE [dbo].[Employee](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [MobileNo] [varchar](50) NULL,  
  5. CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [ID] ASC  
  8. WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10. GO 
Step 2

Add all CRUD Procedures (Insert, Update, Get, GetAll, Delete).

Insert Employee

  1. CREATE PROCEDURE [dbo].[Employee_Insert]  
  2.     @Name Varchar(50)  
  3.     ,@MobileNo Varchar(50)  
  4.     ,@OUTVAL Int OUTPUT  
  5.     ,@OUTMSG Varchar(100) OUTPUT  
  6. AS  
  7. BEGIN  
  8.       
  9.     SET NOCOUNT ON;  
  10.   
  11.     INSERT INTO Employee (Name, MobileNo) VALUES (@Name, @MobileNo)  
  12.   
  13.     SET @OUTVAL = 1  
  14.     SET @OUTMSG = 'Employee Insert Successfully.'  
  15. END 
 Update Employe
  1. CREATE PROCEDURE [dbo].[Employee_Update]  
  2.     @ID Int  
  3.     ,@Name Varchar(50)  
  4.     ,@MobileNo Varchar(50)  
  5.     ,@OUTVAL Int OUTPUT  
  6.     ,@OUTMSG Varchar(100) OUTPUT  
  7. AS  
  8. BEGIN  
  9.       
  10.     SET NOCOUNT ON;  
  11.   
  12.     UPDATE Employee SET Name = @Name  
  13.     , MobileNo = @MobileNo  
  14.     WHERE ID = @ID  
  15.   
  16.     SET @OUTVAL = 1  
  17.     SET @OUTMSG = 'Employee Update Successfully.'  
  18. END 
 Delete Employee
  1. CREATE PROCEDURE [dbo].[Employee_Delete]  
  2.     @ID Int  
  3.     ,@OUTVAL Int OUTPUT  
  4.     ,@OUTMSG Varchar(100) OUTPUT  
  5. AS  
  6. BEGIN  
  7.       
  8.     SET NOCOUNT ON;  
  9.   
  10.     DELETE FROM Employee WHERE ID = @ID  
  11.   
  12.     SET @OUTVAL = 1  
  13.     SET @OUTMSG = 'Employee Delete Successfully.'  
  14. END 
 Get Single Employee Record
  1. CREATE PROCEDURE [dbo].[Employee_Get]  
  2.     @ID Int  
  3. AS  
  4. BEGIN  
  5.     SET NOCOUNT ON;  
  6.   
  7.     SELECT * FROM Employee WHERE ID = @ID  
  8. END 
 Get All Employee Records
  1. CREATE PROCEDURE [dbo].[Employee_GetAll]  
  2. AS  
  3. BEGIN  
  4.     SET NOCOUNT ON;  
  5.   
  6.     SELECT * FROM Employee  
  7. END 

After creating the database from the above script, let's start creating our AngularJS MVC project.

Step 1

Open VS and create the project from File -> New -> Project menu.

Angular
Step 2

Select ASP.NET Web Application (.NET Framework) to create MVC application and set the name and location of the project.
 
Angular
 
Step 3

After setting the name and location of the project, it opens another dialog box. From this dialog, select MVC project and click OK. 
 
Angular 
 
Step 4

After completing all the above steps, add CRUD Demo library reference in Angular JS MVC Project. 
 
Angular

Step 5

Go to Angular JS MVC project Web.config file and add the Connection string.
  1. <connectionStrings>  
  2.     <add name="DefaultConnection" connectionString="Data source=ServerName;Database=DataBase;Uid=UserName;Password=Password" providerName="System.Data.SqlClient" />  
  3. </connectionStrings> 

Controller

After adding ConnectionString in Web.Config file, now, go to Controllers -> HomeController. Inside Home, the controller adds the below namespace for accessing classes of JSON, CRUD etc.

Angular
  1. using CURDDemo;  
  2. using System.Data;  
  3. using Newtonsoft.Json; 

After doing all the above pieces of stuff, let's start creating methods for CRUD operation.

Method 1

Save employee record in the employee table.

  1. public JsonResult Save(EmployeeClass modal)  
  2. {  
  3.     MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Insert(modal);  
  4.     return Json(mRes, JsonRequestBehavior.AllowGet);  

The input parameter is: EmployeeClass

Note

The above function returns MEMBERS.SQLReturnMessageNValue. This class contains code and message returned from SQL Stored Procedure. This method inserts the record in the employee table.
 
Method 2

Update employee record in employee table.
  1. public JsonResult Update(EmployeeClass modal)  
  2. {  
  3.     MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Update(modal);  
  4.     return Json(mRes, JsonRequestBehavior.AllowGet);  

The input parameter is: EmployeeClass

Note

Above function return MEMBERS.SQLReturnMessageNValue this class contains code and message return from SQL Store procedure. This method updates record in the employee table.
 
Method 3

Get the Single record of the employee by employee ID.
  1. public JsonResult Get(Int32 ID)  
  2. {  
  3.     DataTable dt = new EmployeeLogic().Employee_Get(ID);  
  4.   
  5.     string convertDataTableToJson = JsonConvert.SerializeObject(dt);  
  6.   
  7.     return Json(convertDataTableToJson, JsonRequestBehavior.AllowGet);  

An input parameter is: ID (Unique ID of Employee Table)

Note
Above function returns a JSON result. First get employee record in DataTable and convert DataTable to JSON using Newtonsoft.Json then return to view.
 
Method 4

Get the Single record of the employee by employee ID.
  1. public JsonResult GetAll()  
  2. {  
  3.     DataTable dt = new EmployeeLogic().Employee_GetAll();  
  4.   
  5.     string convertDataTableToJson = JsonConvert.SerializeObject(dt);  
  6.   
  7.     return Json(convertDataTableToJson, JsonRequestBehavior.AllowGet);  

Note

Above function returns JSON result. This function gets all the employee records in the DataTable and converts DataTable to JSON and returns to view.
 
Method 5

Delete the employee record by employee ID.
  1. public JsonResult Delete(Int32 ID)  
  2. {  
  3.     MEMBERS.SQLReturnMessageNValue mRes = new EmployeeLogic().Employee_Delete(ID);  
  4.     return Json(mRes, JsonRequestBehavior.AllowGet);  

An input parameter is: ID (Unique ID of Employee Table)

Note

Above function returns MEMBERS.SQLReturnMessageNValue. This class contains code and message returns from SQL Store procedure. This method deletes the record from the employee table.

View

After adding all the above methods in controller let's start coding in MVC View.

First, we set the title tag of view.

  1. @{  
  2.     ViewBag.Title = "CURD Operation With Angular";  

Let's design one form that contains below HTML element.

  1. Hidden field for employee unique id : ng-model="EmpID".
  2. Textbox one for employee name : ng-model="EmployeeName".
  3. Textbox two for employee mobile no : ng-model="MobileNo".
  4. Button for save and update employee record.
  5. Table for display all employee records.

Description of Angular JS directive used in this View.

  1. Set name of the application using ng-app="myApp".
  2. Set name of controller using ng-controller="EmployeeCtrl".
  3. Set ID of HTML element using ng-model="EmployeeName".
  4. Set ng-click for call Save and Update function using ng-click="Save()".
  5. Using ng-repeat="c in EmployeeData" bind all employee records in the table.
Note

For getting HTML element value we have to use "ng-model" and using this directive we can get the value of an HTML control.
  1. <div ng-app="myApp" ng-controller="EmployeeCtrl">  
  2.     <input type="hidden" ng-model="EmpID" ng-init="EmpID='0'" />  
  3.   
  4.     <div class="row">  
  5.         <h3>Employee Form</h3>  
  6.         <div class="form-inline">  
  7.             <div class="form-group">  
  8.                 <input type="text" class="form-control" ng-model="EmployeeName" placeholder="Employee Name">  
  9.             </div>  
  10.             <div class="form-group">  
  11.                 <input type="text" class="form-control" ng-model="MobileNo" placeholder="Mobile No.">  
  12.             </div>  
  13.             <button class="btn btn-primary" ng-click="Save()">Save</button>  
  14.         </div>  
  15.     </div>  
  16.     <br />  
  17.     <div class="row">  
  18.         <h3>Employee Records</h3>  
  19.         <table class="table table-bordered">  
  20.             <thead>  
  21.                 <tr>  
  22.                     <th>ID</th>  
  23.                     <th>Name</th>  
  24.                     <th>Mobile No.</th>  
  25.                     <th>Action</th>  
  26.                 </tr>  
  27.             </thead>  
  28.             <tbody>  
  29.                 <tr ng-repeat="c in EmployeeData">  
  30.                     <td>{{c.ID}}</td>  
  31.                     <td>{{c.Name}}</td>  
  32.                     <td>{{c.MobileNo}}</td>  
  33.                     <td>  
  34.                         <button type="button" class="btn btn-primary" id="{{c.ID}}" ng-click="Get(c.ID)">Edit</button>  
  35.                         <button type="button" class="btn btn-danger" id="{{c.ID}}" ng-click="Delete(c.ID)">Delete</button>  
  36.                     </td>  
  37.                 </tr>  
  38.             </tbody>  
  39.         </table>  
  40.     </div>  
  41. </div> 

Angular JS

First, we need to add @section scripts{ } in MVC view for writing our Angular JS code inside this. Section tag adds all code in _Layout.cshtml page run time.

Now, add Angular JS file in section

  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> 

Let's create AngularJs function step by step.

First, set one variable for access application and controller inside this application by adding the line mentioned below.

  1. var myApp = angular.module("myApp", []); 
Using myApp get the controller and create one call back function for getting the scope of the function. Using $scope we can access all HTML controls values.
  1. myApp.controller("EmployeeCtrl"function ($scope, $http) { }); 

Write the below function code inside myApp.controller ("EmployeeCtrl", function ($scope, $http) { });

Save / Update Code

  1. /* Save and Update Employee */  
  2. $scope.Save = function () {  
  3.   
  4.     var id = $scope.EmpID;  
  5.   
  6.     if (id == 0) {  
  7.         var saveReq = {  
  8.             method: "POST",  
  9.             url: "/Home/Save",  
  10.             data: { ID: $scope.EmpID, Name: $scope.EmployeeName, MobileNo: $scope.MobileNo }  
  11.         }  
  12.   
  13.         $http(saveReq).then(function (mRes) {  
  14.             var o = angular.fromJson(mRes.data)  
  15.             alert(o.Outmsg);  
  16.             $scope.GetAllEmployee();  
  17.         });  
  18.     }  
  19.     else {  
  20.         var updateReq = {  
  21.             method: "POST",  
  22.             url: "/Home/Update",  
  23.             data: { ID: $scope.EmpID, Name: $scope.EmployeeName, MobileNo: $scope.MobileNo }  
  24.         }  
  25.   
  26.         $http(updateReq).then(function (mRes) {  
  27.             var o = angular.fromJson(mRes.data)  
  28.             alert(o.Outmsg);  
  29.             $scope.GetAllEmployee();  
  30.         });  
  31.     }  
  32.   
  33.     $scope.ClearControls();  
  34. }; 
Insert Output
 
Angular

Update Output
 
Angular

Above function calls Save and Update method conditionally. If $scope.EmpID contains "0" Save method is called and $scope.EmpID > "0" so we can call update method. For passing data from view to controller use "data:" parameter of saveReq after that call this request using $http. If the request is successfully called then it returns a message from method. Now convert this result and access its parameters. 
 
Get Single Record Code
  1. /* Get Single Employee Record */  
  2. $scope.Get = function (id) {  
  3.     var getReq = {  
  4.         method: "POST",  
  5.         url: "/Home/Get",  
  6.         data: { ID: id }  
  7.     }  
  8.   
  9.     $http(getReq).then(function (mRes) {  
  10.         $scope.Employee = angular.fromJson(mRes.data);  
  11.   
  12.         $scope.EmpID = $scope.Employee[0].ID;  
  13. f
  14.         $scope.EmployeeName = $scope.Employee[0].Name;  
  15.         $scope.MobileNo = $scope.Employee[0].MobileNo;  
  16.     });  
  17. }; 
Get Output

Angular

Above function gets the result by employee ID and converts JSON and stores in Angular JS "$scope.Employee" object now we can use this object for setting value in HTML control.

 

Get All record code

  1. /* Get All Employee Records */  
  2. $scope.GetAllEmployee = function () {  
  3.     var getallReq = {  
  4.         method: "POST",  
  5.         url: "/Home/GetAll",  
  6.         data: {}  
  7.     }  
  8.   
  9.     $http(getallReq).then(function (mRes) {  
  10.         $scope.EmployeeData = angular.fromJson(mRes.data);  
  11.     });  
  12. }; 
GetAll Output

Angular

The above function retrieves all employee records from the database and returns JSON. After getting JSON we have to convert this into Angular JS list object using "Angular.fromJson(mRes.data);" and pass in "$scope.EmployeeData" this $scope.EmployeeData we are using in table ng-repeat to display all client records.

Call the above function after completing the code,

  1. /* Bind All Employee Records */  
  2. $scope.GetAllEmployee(); 
Delete the employee code,
  1. /* Delete Employee */  
  2. $scope.Delete = function (id) {  
  3.     var updateReq = {  
  4.         method: "POST",  
  5.         url: "/Home/Delete",  
  6.         data: { ID: id }  
  7.     }  
  8.   
  9.     $http(updateReq).then(function (mRes) {  
  10.         var o = angular.fromJson(mRes.data)  
  11.         alert(o.Outmsg);  
  12.         $scope.GetAllEmployee();  
  13.     });  
  14. }; 
The above function deletes the record of the employee by ID and returns code and message class. Convert that class "angular.fromJson(mRes.data)" and alert Outmsg for the display user-friendly message on the browser screen.
 
Clear HTML Controls,
  1. /*Clear controls */  
  2. $scope.ClearControls = function () {  
  3.     $scope.EmpID = 0;  
  4.     $scope.EmployeeName = '';  
  5.     $scope.MobileNo = '';  

Above function clears value of HTML elements.

Note
$scope.GetAllEmployee(); this function is called when the  page loads for the first time. 

$scope.ClearControls(); this function is called when inserting and updating records.