Manage Data (CRUD Operations) Using MVC4 Web API AngularJS

The following are the highlights of this article:

  1. Create a Database. (SchoolManagement).
  2. Create a Table (Student).
  3. Create a MVC 4 application.
  4. Add a WEB API.
  5. Use AngularJs to consume WEB API.
  6. Perform the CRUD (Create, Read, Update & Delete) operations using Angular with WEB API.

Angular

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS is a JavaScript framework. Its goal is to augment browser-based applications with Model–View–Controller (MVC) capability, in an effort to make both development and testing easier. 

This article shows how to manage Student Data.

The following is my Data Table.

design view
Image 1

The following is the script for my Data Table:
  1. CREATE TABLE [dbo].[Student](  
  2.     [StudentID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [Email] [varchar](500) NULL,  
  5.     [Class] [varchar](50) NULL,  
  6.     [EnrollYear] [varchar](50) NULL,  
  7.     [City] [varchar](50) NULL,  
  8.     [Country] [varchar](50) NULL,  
  9.  CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED   
  10. (  
  11.     [StudentID] ASC  
  12. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  13. ON [PRIMARY]  
  14.   
  15. GO  
  16.   
  17. SET ANSI_PADDING OFF  
  18. GO  
Now open Visual Studio and create a project.

mvc web application
Image 2

Select ASP.NET MVC 4 Web Application then click OK.

internet application
Image 3

Now we will add the database. So right-click on the Model then select Add -> ADO.NET Entity Data Model.

entity data model
Image 4

Provide it a name.

item name
Image 5

Enter your database connection properties.

generate from database
Image 6

servername
Image 7

data connection
Image 8

select table name
Image 9

properties
Image 10

Now it is time to add a new Web API controller. So right-click on the Controller then select Add -> Controller.

add controller
Image 11

Here select API controller with read/write actions, using Entity Framework in Template option, select Model class and select Data Context Class ->ADD.

controller name
Image 12

It will add a StudentAPI controller with the following automatically generated code with methods for GET, PUT, POST and DELETE.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web;  
  10. using System.Web.Http;  
  11. using MVC4_WEBApi_Angular_CRUD.Models;  
  12.   
  13. namespace MVC4_WEBApi_Angular_CRUD.Controllers  
  14. {  
  15.     public class StudentsAPIController : ApiController  
  16.     {  
  17.         private SchoolManagementEntities db = new SchoolManagementEntities();  
  18.   
  19.         // GET api/StudentsAPI  
  20.         public IEnumerable<Student> GetStudents()  
  21.         {  
  22.             return db.Student.AsEnumerable();  
  23.         }  
  24.   
  25.         // GET api/StudentsAPI/5  
  26.         public Student GetStudent(int id)  
  27.         {  
  28.             Student student = db.Student.Find(id);  
  29.             if (student == null)  
  30.             {  
  31.                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
  32.             }  
  33.   
  34.             return student;  
  35.         }  
  36.   
  37.         // PUT api/StudentsAPI/5  
  38.         public HttpResponseMessage PutStudent(int id, Student student)  
  39.         {  
  40.             if (ModelState.IsValid && id == student.StudentID)  
  41.             {  
  42.                 db.Entry(student).State = EntityState.Modified;  
  43.   
  44.                 try  
  45.                 {  
  46.                     db.SaveChanges();  
  47.                 }  
  48.                 catch (DbUpdateConcurrencyException)  
  49.                 {  
  50.                     return Request.CreateResponse(HttpStatusCode.NotFound);  
  51.                 }  
  52.   
  53.                 return Request.CreateResponse(HttpStatusCode.OK);  
  54.             }  
  55.             else  
  56.             {  
  57.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  58.             }  
  59.         }  
  60.   
  61.         // POST api/StudentsAPI  
  62.         public HttpResponseMessage PostStudent(Student student)  
  63.         {  
  64.             if (ModelState.IsValid)  
  65.             {  
  66.                 db.Student.Add(student);  
  67.                 db.SaveChanges();  
  68.   
  69.                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, student);  
  70.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = student.StudentID }));  
  71.                 return response;  
  72.             }  
  73.             else  
  74.             {  
  75.                 return Request.CreateResponse(HttpStatusCode.BadRequest);  
  76.             }  
  77.         }  
  78.   
  79.         // DELETE api/StudentsAPI/5  
  80.         public HttpResponseMessage DeleteStudent(int id)  
  81.         {  
  82.             Student student = db.Student.Find(id);  
  83.             if (student == null)  
  84.             {  
  85.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  86.             }  
  87.   
  88.             db.Student.Remove(student);  
  89.   
  90.             try  
  91.             {  
  92.                 db.SaveChanges();  
  93.             }  
  94.             catch (DbUpdateConcurrencyException)  
  95.             {  
  96.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  97.             }  
  98.   
  99.             return Request.CreateResponse(HttpStatusCode.OK, student);  
  100.         }  
  101.   
  102.         protected override void Dispose(bool disposing)  
  103.         {  
  104.             db.Dispose();  
  105.             base.Dispose(disposing);  
  106.         }  
  107.     }  
  108. }  
Now we will add a new controller by right-clicking on the Controller Folder then selecting Add -> Controller.

add new controller
Image 13

Select here Empty MVC controller from (Template) Scaffolding options.

type controller name
Image 14

Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVC4_WEBApi_Angular_CRUD.Controllers  
  8. {  
  9.     public class StudentController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Student/  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.     }  
  19. }  
We will add a View after adding an AngularJs reference so right-click on your project name in Solution Explorer then select Manage NuGet Packages option.

manage NUGET Packages
Image 15

install angular JS
Image 16

downloading
Image 17

After adding an AngularJs reference now create a new folder in the Script folder then do something with MyAngularjsScripts and 3 the JavaScript files named as below.
  1. Module.js
  2. Service.js
  3. Controller.js

Module.js

  1. var app;  
  2. (function () {  
  3.     app = angular.module("crudModule", []);  
  4. })()  
Service.js
  1. app.service('CRUD_OperService'function ($http) {  
  2.   
  3.     //Create new record  
  4.     this.post = function (Student) {        
  5.         var request = $http({  
  6.             method: "post",  
  7.             url: "/api/StudentsAPI",  
  8.             data: Student  
  9.         });  
  10.         return request;  
  11.     }  
  12.   
  13.     //Get Single Records  
  14.     this.get = function (StudentID) {  
  15.         return $http.get("/api/StudentsAPI/" + StudentID);  
  16.     }  
  17.   
  18.     //Get All Student  
  19.     this.getAllStudent = function () {  
  20.         return $http.get("/api/StudentsAPI");  
  21.     }  
  22.   
  23.     //Update the Record  
  24.     this.put = function (StudentID, Student) {  
  25.         var request = $http({  
  26.             method: "put",  
  27.             url: "/api/StudentsAPI/" + StudentID,  
  28.             data: Student  
  29.         });  
  30.         return request;  
  31.     }  
  32.   
  33.     //Delete the Record  
  34.     this.delete = function (StudentID) {  
  35.         var request = $http({  
  36.             method: "delete",  
  37.             url: "/api/StudentsAPI/" + StudentID  
  38.         });  
  39.         return request;  
  40.     }  
  41. });  
Controller.js
  1. app.controller('CRUD_OperController'function ($scope, CRUD_OperService) {  
  2.     $scope.OperType = 1;  
  3.     //1 Mean New Entry  
  4.   
  5.     GetAllRecords();  
  6.     //To Get All Records  
  7.     function GetAllRecords() {  
  8.         var promiseGet = CRUD_OperService.getAllStudent();  
  9.         promiseGet.then(function (pl) { $scope.Students = pl.data },  
  10.               function (errorPl) {  
  11.                   $log.error('Some Error in Getting Records.', errorPl);  
  12.               });  
  13.     }  
  14.   
  15.     //To Clear all input controls.  
  16.     function ClearModels() {  
  17.         $scope.OperType = 1;  
  18.         $scope.StudentID = "";  
  19.         $scope.Name = "";  
  20.         $scope.Email = "";  
  21.         $scope.Class = "";  
  22.         $scope.EnrollYear = "";  
  23.         $scope.City = "";  
  24.         $scope.Country = "";  
  25.     }  
  26.   
  27.    //To Create new record and Edit an existing Record.  
  28.     $scope.save = function () {  
  29.         var Student = {  
  30.             Name: $scope.Name,  
  31.             Email: $scope.Email,  
  32.             Class: $scope.Class,  
  33.             EnrollYear: $scope.EnrollYear,  
  34.             City: $scope.City,  
  35.             Country: $scope.Country  
  36.         };  
  37.         if ($scope.OperType === 1) {  
  38.             var promisePost = CRUD_OperService.post(Student);  
  39.             promisePost.then(function (pl) {  
  40.                 $scope.StudentID = pl.data.StudentID;  
  41.                 GetAllRecords();  
  42.                 ClearModels();  
  43.             }, function (err) {  
  44.                 console.log("Err" + err);  
  45.             });  
  46.         } else {  
  47.             //Edit the record                
  48.             Student.StudentID = $scope.StudentID;  
  49.             var promisePut = CRUD_OperService.put($scope.StudentID, Student);  
  50.             promisePut.then(function (pl) {  
  51.                 $scope.Message = "Student Updated Successfuly";  
  52.                 GetAllRecords();  
  53.                 ClearModels();  
  54.             }, function (err) {  
  55.                 console.log("Err" + err);  
  56.             });  
  57.         }  
  58.     };  
  59.   
  60.     //To Delete Record  
  61.     $scope.delete = function (Student) {  
  62.         var promiseDelete = CRUD_OperService.delete(Student.StudentID);  
  63.         promiseDelete.then(function (pl) {  
  64.             $scope.Message = "Student Deleted Successfuly";  
  65.             GetAllRecords();  
  66.             ClearModels();  
  67.         }, function (err) {  
  68.             console.log("Err" + err);  
  69.         });  
  70.     }  
  71.   
  72.     //To Get Student Detail on the Base of Student ID  
  73.     $scope.get = function (Student) {  
  74.         var promiseGetSingle = CRUD_OperService.get(Student.StudentID);  
  75.   
  76.         promiseGetSingle.then(function (pl) {  
  77.             var res = pl.data;  
  78.             $scope.StudentID = res.StudentID;  
  79.             $scope.Name = res.Name;  
  80.             $scope.Email = res.Email;  
  81.             $scope.Class = res.Class;  
  82.             $scope.EnrollYear = res.EnrollYear;  
  83.             $scope.City = res.City;  
  84.             $scope.Country = res.Country;  
  85.   
  86.             $scope.OperType = 0;  
  87.         },  
  88.                   function (errorPl) {  
  89.                       console.log('Some Error in Getting Details', errorPl);  
  90.                   });  
  91.     }  
  92.   
  93.     //To Clear all Inputs controls value.  
  94.     $scope.clear = function () {  
  95.         $scope.OperType = 1;  
  96.         $scope.StudentID = "";  
  97.         $scope.Name = "";  
  98.         $scope.Email = "";  
  99.         $scope.Class = "";  
  100.         $scope.EnrollYear = "";  
  101.         $scope.City = "";  
  102.         $scope.Country = "";  
  103.     }  
  104.   
  105. });  
Now for StudentControler right-click on the Index method then select Add view.

add view
Image 18

type view name
Image 19

Our Index.cshtml is:
  1. <html data-ng-app="crudModule">  
  2. @{  
  3.     ViewBag.Title = "Manage Student Information using AngularJs, WEB API & MVC4";  
  4. }  
  5.   
  6. <body>  
  7.     <table id="tblContainer" data-ng-controller="CRUD_OperController">  
  8.         <tr>  
  9.             <td>  
  10.                 <table style="border: solid 2px Green; padding: 5px;">  
  11.                     <tr style="height: 30px; background-color: skyblue; color: maroon;">  
  12.                         <th></th>  
  13.                         <th>ID</th>  
  14.                         <th>Name</th>  
  15.                         <th>Email</th>  
  16.                         <th>Class</th>  
  17.                         <th>Year</th>  
  18.                         <th>City</th>  
  19.                         <th>Country</th>  
  20.                         <th></th>  
  21.                         <th></th>  
  22.                     </tr>  
  23.                     <tbody data-ng-repeat="stud in Students">  
  24.                         <tr>  
  25.                             <td></td>  
  26.                             <td><span>{{stud.StudentID}}</span></td>  
  27.                             <td><span>{{stud.Name}}</span></td>  
  28.                             <td><span>{{stud.Email}}</span></td>  
  29.                             <td><span>{{stud.Class}}</span></td>  
  30.                             <td><span>{{stud.EnrollYear}}</span></td>  
  31.                             <td><span>{{stud.City}}</span></td>  
  32.                             <td><span>{{stud.Country}}</span></td>  
  33.                             <td>  
  34.                                 <input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" /></td>  
  35.   
  36.                             <td>  
  37.                                 <input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" /></td>  
  38.                         </tr>  
  39.                     </tbody>  
  40.                 </table>  
  41.   
  42.             </td>  
  43.         </tr>  
  44.         <tr>  
  45.             <td>  
  46.                 <div style="color: red;">{{Message}}</div>  
  47.                 <table style="border: solid 4px Red; padding: 2px;">  
  48.                     <tr>  
  49.                         <td></td>  
  50.                         <td>  
  51.                             <span>Student ID</span>  
  52.                         </td>  
  53.                         <td>  
  54.                             <input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />  
  55.                         </td>  
  56.                     </tr>  
  57.                     <tr>  
  58.                         <td></td>  
  59.                         <td>  
  60.                             <span>Student Name</span>  
  61.                         </td>  
  62.                         <td>  
  63.                             <input type="text" id="sName" required data-ng-model="Name" />  
  64.                         </td>  
  65.                     </tr>  
  66.                     <tr>  
  67.                         <td></td>  
  68.                         <td>  
  69.                             <span>Email</span>  
  70.                         </td>  
  71.                         <td>  
  72.                             <input type="text" id="sEmail" required data-ng-model="Email" />  
  73.                         </td>  
  74.                     </tr>  
  75.                     <tr>  
  76.                         <td></td>  
  77.                         <td>  
  78.                             <span>Class</span>  
  79.                         </td>  
  80.                         <td>  
  81.                             <input type="text" id="sClass" required data-ng-model="Class" />  
  82.                         </td>  
  83.                     </tr>  
  84.                     <tr>  
  85.                         <td></td>  
  86.                         <td>  
  87.                             <span>Enrollement Year</span>  
  88.                         </td>  
  89.                         <td>  
  90.                             <input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />  
  91.                         </td>  
  92.                     </tr>  
  93.                     <tr>  
  94.                         <td></td>  
  95.                         <td>  
  96.                             <span>City</span>  
  97.                         </td>  
  98.                         <td>  
  99.                             <input type="text" id="sCity" required data-ng-model="City" />  
  100.                         </td>  
  101.                     </tr>  
  102.                     <tr>  
  103.                         <td></td>  
  104.                         <td>  
  105.                             <span>Country</span>  
  106.                         </td>  
  107.                         <td>  
  108.                             <input type="text" id="sCountry" required data-ng-model="Country" />  
  109.                         </td>  
  110.                     </tr>  
  111.                     <tr>  
  112.                         <td></td>  
  113.                         <td></td>  
  114.                         <td>  
  115.                             <input type="button" id="save" value="Save" data-ng-click="save()" />  
  116.   
  117.                             <input type="button" id="Clear" value="Clear" data-ng-click="clear()" />  
  118.                         </td>  
  119.                     </tr>  
  120.                 </table>  
  121.   
  122.             </td>  
  123.         </tr>  
  124.   
  125.     </table>  
  126. </body>  
  127. </html>  
  128.   
  129. <script src="~/Scripts/angular.js"></script>  
  130. <script src="~/Scripts/angular-route.js"></script>  
  131. <script src="~/Scripts/MyAngularjsScripts/Module.js"></script>  
  132. <script src="~/Scripts/MyAngularjsScripts/Service.js"></script>  
  133. <script src="~/Scripts/MyAngularjsScripts/Controller.js"></script>  
Now run the application. You can set a start-up URI from the Route.config file in the APP_START folder like the following:

cs coding
Image 20

Run application: See your all records.

From here you can add a new record, edit any record and delete any record.

ajjularJS
Image 21

web api
Image 22

edit record
Image 23