Performing CRUD Operation Using AngularJS And Web API

In this article, we will learn basic CRUD operations, using AngularJS and Web API with a sample Application.

I have uploaded the full source code @github and you may clone/download.

In this article, we are going to explore how to

  • Use Database SQL Server.
  • Use MVC Application.
  • Use Entity Framework (Database First Approach).
  • Use AngularJS.
  • Use ASP.NET Web API.

Let’s get started with the steps

Create database

Before we get started with IDE, let’s create a new database named “StudentDB” and create a sample table named “tblStudent”. The script is given below.

  1. USE[StudentDB]  
  2. GO  
  3. /****** Object: Table [dbo].[tblStudent] Script Date: 11/24/2016 1:36:13 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE TABLE[dbo].[tblStudent](  
  9.     [StudentID][int] IDENTITY(1, 1) NOT NULL, [FirstName][nvarchar](50) NULL, [LastName][nvarchar](50) NULL, [Email][nvarchar](50) NULL, [Address][nvarchar](50) NULL, CONSTRAINT[PK_tblStudent] PRIMARY KEY CLUSTERED(  
  10.         [StudentID] ASC) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _ ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]) ON[PRIMARY]  
  11. GO // This is just a sample script. Paste your real code (javascript or HTML) here.  
  12. if ('this_is' == /an_example/) {  
  13.     of_beautifier();  
  14. else {  
  15.     var a = b ? (c % d) : e[f];  
  16. }  
We are done with our database. Now, let’s go for creating a simple MVC Application Start Visual Studio, click New Project >>

Database

The below window will appear on screen:

Database

After clicking a new ASP.NET Project, Window will appear on the screen.

Database

Solution creation is done with loading all the required files. Given below is the picture of solution structure.

Database

Let's go Explore Solution Structure

We know that ASP.NET MVC is a Web Application framework developed by Microsoft. This structure works with Model, View and Controller.
  • Model
    Classes represent the data of the solution and it enforces business.

  • View
    Simple world view means UI (User Interface) which dynamically generates HTML responses.

  • Controller
    A Controller is the link between the user and system. It handles incoming Browser requests and after processing, using model data or specific task returns a response to the Browser.

Now, we will Add AngularJS in our solution.

With right button, click on solution, click Manage NuGet Packages to add AngularJS reference.

Database

After clicking the Install button, load the AngularJS files. Kindly find the screenshot mentioned below.

Database

Now, we will create ScriptsNg folder in solution, we will create 4 folders within ScriptsNg.

  1. Controller
  2. Directive
  3. Module
  4. Service

Controller

AngularJS Controller controls the data between model and view in an Application, keeping  all Controller Script files within Controller folder.

Directive

AngularJS Directive extends HTML with a new attribute, keeping all Directive files within Directive folder.

Module

Modules are used to separate logic, say Services, controllers, Application etc. and keep the code clean, keep all the module files in module folder.

Service

Service is a function, keeping all the customized Service files within Service folder. Now, we will create a JS file named “app.js” within module folder. The code is mentioned below.

  1. var app;  
  2. (function() {  
  3.     'use strict'//Defines that JavaScript code should be executed in "strict mode"  
  4.     app = angular.module('myapp', []);  
  5. })();  
We will create Controller named “StudentCtrl” within Controller folder. The code is given below.
  1. app.controller('StudentCtrl', ['$scope',  
  2.     function($scope) {  
  3.         $scope.Message = 'Hellow World';  
  4.     }  
  5. ]);  
We will create StudentController class within MVC Controller folder. The code is given below.
  1. public class StudentController: Controller {  
  2.     // GET: Student  
  3.     public ActionResult Index() {  
  4.         return View();  
  5.     }  
  6. }  
We have to create view. Below is the picture on how to create view.

Database

View has been created successfully. We will add some code within index view for checking if AngularJS will work. The code is mentioned below.
  1. <div ng-app="myapp">  
  2.     <div ng-controller="StudentCtrl"> {{Message}} </div>  
  3. </div>  
  4. <script src="~/Scripts/angular.min.js"></script>  
  5. <script src="~/ScriptsNg/Module/app.js"></script>  
  6. <script src="~/ScriptsNg/Controller/StudentCtrl.js"></script>  
After running Angular JS, the work has been done for which the result has been given below.

Database

Entity Framework

After clicking References, we can see that Entity framework already exists in our solution.

Create Entity Data Model

Right click on your model folder and click new, select ADO.NET Entity Data Model. Follow the steps given. Once you have done the process, we can see the edmx file and other files in your model folder. It is named StudentDBEntities and the screenshot of edmx model is mentioned below.

Database

Now our solution is ready for crud operation.

Now, we have created a folder named API in our solution. With right button, click add and click controller, which shows the Window, mentioned below.

Database

Add controller name. The image is shown below.

Database

Our StudentController's API has been created.

For Save
  1. namespace CrudOperation.api {  
  2.     // Route   
  3.     [RoutePrefix("/api/Student")]  
  4.     public class StudentController: ApiController {  
  5.         // StudentDBEntities object point  
  6.         StudentDBEntities dbContext = null;  
  7.         // Constructor   
  8.         public StudentController() {  
  9.                 // create instance of an object  
  10.                 dbContext = new StudentDBEntities();  
  11.             }  
  12.             [ResponseType(typeof(tblStudent))]  
  13.             [HttpPost]  
  14.         public HttpResponseMessage SaveStudent(tblStudent astudent) {  
  15.             int result = 0;  
  16.             try {  
  17.                 dbContext.tblStudents.Add(astudent);  
  18.                 dbContext.SaveChanges();  
  19.                 result = 1;  
  20.             } catch (Exception e) {  
  21.                 result = 0;  
  22.             }  
  23.             return Request.CreateResponse(HttpStatusCode.OK, result);  
  24.         }  
  25.     }  
  26. }  
We have completed the save method of student. We have added some code within studentCtrl. The code is given below.
  1. app.controller('StudentCtrl', ['$scope''CrudService',  
  2.     function($scope, CrudService) {  
  3.         // Base Url   
  4.         var baseUrl = '/api/Student/';  
  5.         $scope.btnText = "Save";  
  6.         $scope.studentID = 0;  
  7.         $scope.SaveUpdate = function() {  
  8.             var student = {  
  9.                 FirstName: $scope.firstName,  
  10.                 LastName: $scope.lasttName,  
  11.                 Email: $scope.email,  
  12.                 Address: $scope.adress,  
  13.                 StudentID: $scope.studentID  
  14.             }  
  15.             if ($scope.btnText == "Save") {  
  16.                 var apiRoute = baseUrl + 'SaveStudent/';  
  17.                 var saveStudent = CrudService.post(apiRoute, student);  
  18.                 saveStudent.then(function(response) {  
  19.                     if (response.data != "") {  
  20.                         alert("Data Save Successfully");  
  21.                         $scope.Clear();  
  22.                     } else {  
  23.                         alert("Some error");  
  24.                     }  
  25.                 }, function(error) {  
  26.                     console.log("Error: " + error);  
  27.                 });  
  28.             }  
  29.         }  
  30.         $scope.Clear = function() {  
  31.             $scope.studentID = 0;  
  32.             $scope.firstName = "";  
  33.             $scope.lasttName = "";  
  34.             $scope.email = "";  
  35.             $scope.adress = "";  
  36.         }  
  37.     }  
  38. ]);  
In the code, mentioned above, we can see "CrudService" is a Service, where we have written some HTTP Verb for inserting, updateing, deleting, and fetching the data from the database. The code is mentioned below.
  1. app.service('CrudService'function($http) {  
  2.     var urlGet = '';  
  3.     this.post = function(apiRoute, Model) {  
  4.         var request = $http({  
  5.             method: "post",  
  6.             url: apiRoute,  
  7.             data: Model  
  8.         });  
  9.         return request;  
  10.     }  
  11.     this.put = function(apiRoute, Model) {  
  12.         var request = $http({  
  13.             method: "put",  
  14.             url: apiRoute,  
  15.             data: Model  
  16.         });  
  17.         return request;  
  18.     }  
  19.     this.delete = function(apiRoute) {  
  20.         var request = $http({  
  21.             method: "delete",  
  22.             url: apiRoute  
  23.         });  
  24.         return request;  
  25.     }  
  26.     this.getAll = function(apiRoute) {  
  27.         urlGet = apiRoute;  
  28.         return $http.get(urlGet);  
  29.     }  
  30.     this.getbyID = function(apiRoute, studentID) {  
  31.         urlGet = apiRoute + '/' + studentID;  
  32.         return $http.get(urlGet);  
  33.     }  
  34. });  
We have to design our UI (User Interface) for Crud Operation. As stated above, we have already created index view. Now, we will use this view. The code is given below.
  1. <div ng-app="myapp">  
  2.     <div ng-controller="StudentCtrl">  
  3.         <form novalidate name="frmStudent" id="frmStudent" class="form-horizontal row-border"> <br />  
  4.             <div class="col-md-12">  
  5.                 <div class="form-group"> <label class="col-md-4 control-label" for="input17"> First Name</label>  
  6.                     <div class="col-md-7"> <input type="text" id="idFirstName" class="form-control" name="nameFirstName" ng-model="firstName" /> </div>  
  7.                 </div>  
  8.                 <div class="form-group"> <label class="col-md-4 control-label" for="input17"> Last Name</label>  
  9.                     <div class="col-md-7"> <input type="text" id="idLastName" class="form-control" name="nameFirstName" ng-model="lasttName" /> </div>  
  10.                 </div>  
  11.                 <div class="form-group"> <label class="col-md-4 control-label" for="input17"> Email</label>  
  12.                     <div class="col-md-7"> <input type="text" id="idEmail" class="form-control" name="nameEmail" ng-model="email" /> </div>  
  13.                 </div>  
  14.                 <div class="form-group"> <label class="col-md-4 control-label" for="input17"> Address</label>  
  15.                     <div class="col-md-7"> <input type="text" id="idAddress" class="form-control" name="nameAdress" ng-model="adress" /> </div>  
  16.                 </div>  
  17.                 <div class="form-group">  
  18.                     <div class="col-md-4"> </div>  
  19.                     <div class="col-md-7"> <span id="save" class="btn btn-success margin-right-btn" ng-click="SaveUpdate()">  
  20. <i class="icon-save"></i> {{btnText}}  
  21. </span> </div>  
  22.                 </div>  
  23.             </div>  
  24.         </form>  
  25.     </div>  
  26. </div>  
  27. <script src="~/Scripts/angular.min.js"></script>  
  28. <script src="~/ScriptsNg/Module/app.js"></script>  
  29. <script src="~/ScriptsNg/Controller/StudentCtrl.js"></script>  
  30. <script src="~/ScriptsNg/Services/CrudService.js"></script>  
Let’s go explain the code

In the code, mentioned above, we can see that there are some unfamiliar things that are used for AngularJS.
  • ng-app="myapp"
    Here, ng-app is the root element of the AngularJS and “myapp" is the name of app.js.

  • ng-controller="StudentCtrl"
    Here, ng-controller directive adds a controller to your Application and StudentCtrl is the name of controller. We can write the code and make function and variables.

  • ng-model
    Here, directive binds the value of HTML controls.

Note

Keep in mind that AngularJS2  is a way to bind the data. After running, we get UI, mentioned below.

Database

For Fetch Data form Database

Our Save is done. Now, we will fetch the data from the database. We will add GetStudents method in StudentController's API Controller. The code is mentioned below.

  1. [ResponseType(typeof(tblStudent))]  
  2. [HttpGet]  
  3. public List < tblStudent > GetStudents() {  
  4.     List < tblStudent > students = null;  
  5.     try {  
  6.         students = dbContext.tblStudents.ToList();  
  7.     } catch (Exception e) {  
  8.         students = null;  
  9.     }  
  10.     return students;  
  11. }  
We have added some code within studentCtrl. The code is given below.
  1. $scope.GetStudents = function() {  
  2.     var apiRoute = baseUrl + 'GetStudents/';  
  3.     var student = CrudService.getAll(apiRoute);  
  4.     student.then(function(response) {  
  5.         debugger  
  6.         $scope.studnets = response.data;  
  7.     }, function(error) {  
  8.         console.log("Error: " + error);  
  9.     });  
  10. }  
  11. $scope.GetStudents();  
We have added some code Index view to show students list. The code is given below.
  1. <table class="table table-hover general-table">  
  2.     <thead class="grid-top-panel">  
  3.         <tr>  
  4.             <th style="display:none">StudentID</th>  
  5.             <th>First Name</th>  
  6.             <th>Last Name</th>  
  7.             <th>Email</th>  
  8.             <th>Address</th>  
  9.             <th>Action</th>  
  10.         </tr>  
  11.     </thead>  
  12.     <tbody>  
  13.         <tr ng-repeat="dataModel in students">  
  14.             <td style="display:none">{{dataModel.StudentID}}</td>  
  15.             <td> {{dataModel.FirstName}}</td>  
  16.             <td> {{dataModel.LastName}}</td>  
  17.             <td>{{dataModel.Email}}</td>  
  18.             <td>{{dataModel.Address}}</td>  
  19.             <td style="text-align:right; color:white"> <span>   
  20. <span id="save" class="btn btn-primary margin-right-btn"   
  21. ng-click="GetStudentByID(dataModel)">  
  22. Edit  
  23. </span> </span>  
  24.             </td>  
  25.             <td style="text-align:right; color:white"> <span>  
  26. <span id="save" class="btn btn-danger margin-right-btn"   
  27. ng-click="DeleteStudent(dataModel)">  
  28. Delete  
  29. </span> </span>  
  30.             </td>  
  31.         </tr>  
  32.     </tbody>  
  33.     <tfoot></tfoot>  
  34. </table>  
We have just added data within HTML table.

Database

For Update

We have to create two methods in StudentController’s API for update. First, we will get student info by studentID after changing student’s properties and we have to update.
  1. First Method GetStudentByID[Route("GetStudentByID/{studentID:int}")]  
  2.     [ResponseType(typeof(tblStudent))]  
  3.     [HttpGet]  
  4. public tblStudent GetStudentByID(int studentID) {  
  5.     tblStudent astudent = null;  
  6.     try {  
  7.         astudent = dbContext.tblStudents.Where(x => x.StudentID == studentID).SingleOrDefault();  
  8.     } catch (Exception e) {  
  9.         astudent = null;  
  10.     }  
  11.     return astudent;  
  12. }  
We have to use GetStudentByID method for getting specific student data by studentID StudentCtrl. The code is given below.
  1. $scope.GetStudentByID = function(dataModel) {  
  2.     debugger  
  3.     var apiRoute = baseUrl + 'GetStudentByID';  
  4.     var student = CrudService.getbyID(apiRoute, dataModel.StudentID);  
  5.     student.then(function(response) {  
  6.         $scope.studentID = response.data.StudentID;  
  7.         $scope.firstName = response.data.FirstName;  
  8.         $scope.lasttName = response.data.LastName;  
  9.         $scope.email = response.data.Email;  
  10.         $scope.adress = response.data.Address;  
  11.         $scope.btnText = "Update";  
  12.     }, function(error) {  
  13.         console.log("Error: " + error);  
  14.     });  
  15. }  
Now, we will check what will work. After clicking edit button, we get the result, mentioned below.

Database

Second, we will update our student data, so we have to create UpdateStudent method. The code is mentioned below.
  1. [ResponseType(typeof(tblStudent))]  
  2. [HttpPut]  
  3. public HttpResponseMessage UpdateStudent(tblStudent astudent) {  
  4.     int result = 0;  
  5.     try {  
  6.         dbContext.tblStudents.Attach(astudent);  
  7.         dbContext.Entry(astudent).State = EntityState.Modified;  
  8.         dbContext.SaveChanges();  
  9.         result = 1;  
  10.     } catch (Exception e) {  
  11.         result = 0;  
  12.     }  
  13.     return Request.CreateResponse(HttpStatusCode.OK, result);  
  14. }  
We will modify our SaveUpdate method for updating.
  1. $scope.SaveUpdate = function() {  
  2.     var student = {  
  3.         FirstName: $scope.firstName,  
  4.         LastName: $scope.lasttName,  
  5.         Email: $scope.email,  
  6.         Address: $scope.adress,  
  7.         StudentID: $scope.studentID  
  8.     }  
  9.     if ($scope.btnText == "Save") {  
  10.         var apiRoute = baseUrl + 'SaveStudent/';  
  11.         var saveStudent = CrudService.post(apiRoute, student);  
  12.         saveStudent.then(function(response) {  
  13.             if (response.data != "") {  
  14.                 alert("Data Save Successfully");  
  15.                 $scope.GetStudents();  
  16.                 $scope.Clear();  
  17.             } else {  
  18.                 alert("Some error");  
  19.             }  
  20.         }, function(error) {  
  21.             console.log("Error: " + error);  
  22.         });  
  23.     } else {  
  24.         var apiRoute = baseUrl + 'UpdateStudent/';  
  25.         var UpdateStudent = CrudService.put(apiRoute, student);  
  26.         UpdateStudent.then(function(response) {  
  27.             if (response.data != "") {  
  28.                 alert("Data Update Successfully");  
  29.                 $scope.GetStudents();  
  30.                 $scope.Clear();  
  31.             } else {  
  32.                 alert("Some error");  
  33.             }  
  34.         }, function(error) {  
  35.             console.log("Error: " + error);  
  36.         });  
  37.     }  
  38. }  
Now, we will check what will work. The image is shown below.

Database

For Delete

Now, we have to add delete method within StudentController's API. The code is mentioned below.
  1. [ResponseType(typeof(tblStudent))]  
  2. [HttpDelete]  
  3. public HttpResponseMessage DeleteStudent(int id) {  
  4.     int result = 0;  
  5.     try {  
  6.         var student = dbContext.tblStudents.Where(x => x.StudentID == id).FirstOrDefault();  
  7.         dbContext.tblStudents.Attach(student);  
  8.         dbContext.tblStudents.Remove(student);  
  9.         dbContext.SaveChanges();  
  10.         result = 1;  
  11.     } catch (Exception e) {  
  12.         result = 0;  
  13.     }  
  14.     return Request.CreateResponse(HttpStatusCode.OK, result);  
  15. }  
We will add Delete method within AngularJs Controller named "StudentCtrl". The code is given below.
  1. $scope.DeleteStudent = function(dataModel) {  
  2.     debugger  
  3.     var apiRoute = baseUrl + 'DeleteStudent/' + dataModel.StudentID;  
  4.     var deleteStudent = CrudService.delete(apiRoute);  
  5.     deleteStudent.then(function(response) {  
  6.         if (response.data != "") {  
  7.             alert("Data Delete Successfully");  
  8.             $scope.GetStudents();  
  9.             $scope.Clear();  
  10.         } else {  
  11.             alert("Some error");  
  12.         }  
  13.     }, function(error) {  
  14.         console.log("Error: " + error);  
  15.     });  
  16. }  
After deleting student info, the output is displayed in the image, mentioned below.

Database

Hope, this will be very helpful.