CRUD Operations in MVC4 Using AngularJS and WCF REST Services

This article shows how to do Create, Retrieve, Update and Delete (CRUD) operations in MVC4 using AngularJS and WCF REST Services.

In my previous article I showed how to do CRUD operations in MVC4 using AngularJs and the Web API.

Manage Data (CRUD Operations) Using MVC4 Web API AngularJS: Manage Data (CRUD Operations) Using MVC4 Web API AngularJS.

Now in this article I will show how to do Create, Retrieve, Update and Delete (CRUD) operations in MVC4 using AngularJS and WCF REST Services.

The following are the highlights of this article:

  1. Create a Database. (SchoolManagement).
  2. Create a Table (Student).
  3. Create a WCF REST Service Application to do CRUD operations.
  4. Create a MVC 4 application and use AngularJs to consume WCF REST service.
  5. Perform the CRUD (Create, Read, Update & Delete) operations.

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.

REST

REST
stands for Representational State Transfer. This is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

When we talk about the database as a resource, we usually talk in terms of Create, Retrieve, Update and Delete (CRUD) operations. Now the philosophy of REST is that for a remote resource all these operations should be possible and they should be possible using simple HTTP protocols.

Now the basic CRUD operations are mapped to the HTTP protocols in the following manner:

  • GET: Retrieve the required data (representation of data) from the remote resource.

  • POST: Update the current representation of the data on the remote server.

  • PUT: Insert new data.

  • DELETE: Delete the specified data from the remote server.

Now we will go step-by-step.

The following is my data table.

data table
Image 1

The following  is the script of 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  
So first we need to create the WCF REST Service. So use the following procedure.

Open Visual Studio and select "File" -> "New" -> "Project..." then select WCF in the left Side then select WCF Service Application then click OK.

wcf service
Image 2

Now delete the IService.cs and Service.cs files.

is service
Image 3

Now right-click on the project in the Solution Explorer then select Add New Item then select WCF Service then name it as EmployeeService.

new wcf service
Image 4

Now I will create a Data Contract as StudentDataContract.

Right-click on the project in the Solution Explorer then select Add New Item then add a .cs file and use the following code:

new class
Image 5
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Runtime.Serialization;  
  6.   
  7. namespace WCF_REST_Service  
  8. {  
  9.     public class StudentDataContract  
  10.     {  
  11.         [DataContract]  
  12.         public class EmployeeDataContract  
  13.         {  
  14.             [DataMember]  
  15.             public string StudentID { getset; }  
  16.   
  17.             [DataMember]  
  18.             public string Name { getset; }  
  19.   
  20.             [DataMember]  
  21.             public string Email { getset; }  
  22.   
  23.             [DataMember]  
  24.             public string Class { getset; }  
  25.   
  26.             [DataMember]  
  27.             public string EnrollYear { getset; }  
  28.   
  29.             [DataMember]  
  30.             public string City { getset; }  
  31.   
  32.             [DataMember]  
  33.             public string Country { getset; }  
  34.         }  
  35.   
  36.     }  
  37. }  
Now it is time to add your database to your application. So create a new folder name as the Model in your project. Now right-click on the Model folder and select Add -> New Item.

add new item
Image 6

Select the ADO.NET Entity Data Model.

ado dotnet
Image 7

model contain
Image 8

Here click on New Connection then enter your SQL Server Details then select your database.

select server
Image 9

select data connection
Image 10

select table
Image 11

model
Image 12

Now open the IStudentService.cs file to define an interface: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCF_REST_Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IStudentService" in both code and config
ile together.

[ServiceContract]
public interface IStudentService
{

[OperationContract]
[WebInvoke(Method = "GET",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/GetAllStudent/")]
List<StudentDataContract> GetAllStudent();

[
OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/GetStudentDetails/{StudentId}")]
StudentDataContract GetStudentDetails(string StudentId);

[
OperationContract]
[WebInvoke(Method = "POST",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/AddNewStudent")]
bool AddNewStudent(StudentDataContract student);

[OperationContract]
[WebInvoke(Method = "PUT",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "/UpdateStudent")]
void UpdateStudent(StudentDataContract contact);

[OperationContract]
[WebInvoke(Method = "DELETE",
   RequestFormat = WebMessageFormat.Json,
   ResponseFormat = WebMessageFormat.Json,
   UriTemplate = "DeleteStudent/{StudentId}")]
void DeleteStudent(string StudentId);

}

}

Now Open StudentService.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using WCF_REST_Service.Model;  
  8.   
  9. namespace WCF_REST_Service  
  10. {  
  11.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.  
  12.     // NOTE: In order to launch WCF Test Client for testing this service, please select StudentService.svc or StudentService.svc.cs at the Solution Explorer and start debugging.  
  13.     public class StudentService : IStudentService  
  14.     {  
  15.         SchoolManagementEntities ctx;  
  16.   
  17.         public StudentService()  
  18.         {  
  19.             ctx = new SchoolManagementEntities();  
  20.         }  
  21.   
  22.         public List<StudentDataContract> GetAllStudent()  
  23.         {  
  24.             var query = (from a in ctx.Student  
  25.                          select a).Distinct();  
  26.   
  27.             List<StudentDataContract> studentList = new List<StudentDataContract>();  
  28.   
  29.             query.ToList().ForEach(rec =>  
  30.             {  
  31.                 studentList.Add(new StudentDataContract  
  32.                 {  
  33.                     StudentID = Convert.ToString(rec.StudentID),  
  34.                     Name = rec.Name,  
  35.                     Email = rec.Email,  
  36.                     EnrollYear = rec.EnrollYear,  
  37.                     Class = rec.Class,  
  38.                     City = rec.City,  
  39.                     Country = rec.Country  
  40.                 });  
  41.             });  
  42.             return studentList;  
  43.         }  
  44.   
  45.         public StudentDataContract GetStudentDetails(string StudentId)  
  46.         {  
  47.             StudentDataContract student = new StudentDataContract();  
  48.   
  49.             try  
  50.             {  
  51.                 int Emp_ID = Convert.ToInt32(StudentId);  
  52.                 var query = (from a in ctx.Student  
  53.                              where a.StudentID.Equals(Emp_ID)  
  54.                              select a).Distinct().FirstOrDefault();  
  55.   
  56.                 student.StudentID = Convert.ToString(query.StudentID);  
  57.                 student.Name = query.Name;  
  58.                 student.Email = query.Email;  
  59.                 student.EnrollYear = query.EnrollYear;  
  60.                 student.Class = query.Class;  
  61.                 student.City = query.City;  
  62.                 student.Country = query.Country;  
  63.             }  
  64.             catch (Exception ex)  
  65.             {  
  66.                 throw new FaultException<string>  
  67.                         (ex.Message);  
  68.             }  
  69.             return student;  
  70.         }  
  71.   
  72.         public bool AddNewStudent(StudentDataContract student)  
  73.         {  
  74.             try  
  75.             {  
  76.                 Student std = ctx.Student.Create();  
  77.                 std.Name = student.Name;  
  78.                 std.Email = student.Email;  
  79.                 std.Class = student.Class;  
  80.                 std.EnrollYear = student.EnrollYear;  
  81.                 std.City = student.City;  
  82.                 std.Country = student.Country;  
  83.   
  84.                 ctx.Student.Add(std);  
  85.                 ctx.SaveChanges();  
  86.             }  
  87.             catch (Exception ex)  
  88.             {  
  89.                 throw new FaultException<string>  
  90.                         (ex.Message);  
  91.             }  
  92.             return true;  
  93.         }  
  94.   
  95.         public void UpdateStudent(StudentDataContract student)  
  96.         {  
  97.             try  
  98.             {  
  99.                 int Stud_Id = Convert.ToInt32(student.StudentID);  
  100.                 Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();  
  101.                 std.Name = student.Name;  
  102.                 std.Email = student.Email;  
  103.                 std.Class = student.Class;  
  104.                 std.EnrollYear = student.EnrollYear;  
  105.                 std.City = student.City;  
  106.                 std.Country = student.Country;  
  107.   
  108.                 ctx.SaveChanges();  
  109.             }  
  110.             catch (Exception ex)  
  111.             {  
  112.                 throw new FaultException<string>  
  113.                         (ex.Message);  
  114.             }  
  115.         }  
  116.   
  117.         public void DeleteStudent(string StudentId)  
  118.         {  
  119.             try  
  120.             {  
  121.                 int Stud_Id = Convert.ToInt32(StudentId);  
  122.                 Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();  
  123.                 ctx.Student.Remove(std);  
  124.                 ctx.SaveChanges();  
  125.             }  
  126.             catch (Exception ex)  
  127.             {  
  128.                 throw new FaultException<string>  
  129.                         (ex.Message);  
  130.             }  
  131.         }  
  132.     }  
  133. }  
Now make the following changes in your WCF application web.config file:
  1. <system.serviceModel>  
  2.     <behaviors>  
  3.       <serviceBehaviors>  
  4.         <behavior>  
  5.           <!-- To avoid disclosing metadata information, set the values below to false before deployment -->  
  6.           <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />  
  7.           <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->  
  8.           <serviceDebug includeExceptionDetailInFaults="false" />  
  9.         </behavior>  
  10.       </serviceBehaviors>  
  11.       <endpointBehaviors>  
  12.         <behavior>  
  13.           <webHttp helpEnabled="True"/>  
  14.         </behavior>  
  15.       </endpointBehaviors>  
  16.     </behaviors>  
  17.     <protocolMapping>  
  18.       <add binding="webHttpBinding" scheme="http" />  
  19.     </protocolMapping>  
  20.     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />  
  21.   </system.serviceModel>  
Now our WCF REST Service is ready; run the WCF REST service.

student service
Image 13

It is now time to create a new MVC application. So right-click on your solution and add a new project as below:

add new project
Image 14

asp mvc application
Image 15

internet application
Image 16

Now, add your WCF Service URL to your MVC application. You can host your WCF service in IIS or you can run it and discover the URL locally like the following.

Right-click on your MVC project then select Add Service Reference.

mvc angularJS
Image 17

select namespace
Image 18

Now it is time to add the AngularJs reference. So right-click on your MVC project name in the Solution Explorer then select Add NuGet Packages.

manage nuget packages
Image 19

AngulaJS
Image 20

Now create a new folder (MyScripts) under the Scripts Folder. Here add the following 3 JavaScript files: 
  1. Modules.JS
  2. Controllers.JS
  3. Services.JS

1. Module.JS

  1. /// <reference path="../angular.min.js" />  
  2. var app;  
  3.   
  4. (function () {  
  5. app = angular.module("RESTClientModule", []);  
  6. })();  
2. Controller.JS
  1. /// <reference path="../angular.min.js" />  
  2. /// <reference path="Modules.js" />  
  3. /// <reference path="Services.js" />  
  4.   
  5. app.controller("CRUD_AngularJs_RESTController"function ($scope, CRUD_AngularJs_RESTService) {  
  6.   
  7.     $scope.OperType = 1;  
  8.     //1 Mean New Entry  
  9.   
  10.     GetAllRecords();  
  11.     //To Get All Records  
  12.     function GetAllRecords() {  
  13.         var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();  
  14.         promiseGet.then(function (pl) { $scope.Students = pl.data },  
  15.               function (errorPl) {  
  16.                   $log.error('Some Error in Getting Records.', errorPl);  
  17.               });  
  18.     }  
  19.   
  20.     //To Clear all input controls.  
  21.     function ClearModels() {  
  22.         $scope.OperType = 1;  
  23.         $scope.StudentID = "";  
  24.         $scope.Name = "";  
  25.         $scope.Email = "";  
  26.         $scope.Class = "";  
  27.         $scope.EnrollYear = "";  
  28.         $scope.City = "";  
  29.         $scope.Country = "";  
  30.     }  
  31.   
  32.     //To Create new record and Edit an existing Record.  
  33.     $scope.save = function () {  
  34.         var Student = {  
  35.             Name: $scope.Name,  
  36.             Email: $scope.Email,  
  37.             Class: $scope.Class,  
  38.             EnrollYear: $scope.EnrollYear,  
  39.             City: $scope.City,  
  40.             Country: $scope.Country  
  41.         };  
  42.         if ($scope.OperType === 1) {  
  43.             var promisePost = CRUD_AngularJs_RESTService.post(Student);  
  44.             promisePost.then(function (pl) {  
  45.                 $scope.StudentID = pl.data.StudentID;  
  46.                 GetAllRecords();  
  47.   
  48.                 ClearModels();  
  49.             }, function (err) {  
  50.                 console.log("Some error Occured" + err);  
  51.             });  
  52.         } else {  
  53.             //Edit the record      
  54.             debugger;  
  55.             Student.StudentID = $scope.StudentID;  
  56.             var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);  
  57.             promisePut.then(function (pl) {  
  58.                 $scope.Message = "Student Updated Successfuly";  
  59.                 GetAllRecords();  
  60.                 ClearModels();  
  61.             }, function (err) {  
  62.                 console.log("Some Error Occured." + err);  
  63.             });  
  64.         }  
  65.     };  
  66.   
  67.     //To Get Student Detail on the Base of Student ID  
  68.     $scope.get = function (Student) {  
  69.         var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);  
  70.         promiseGetSingle.then(function (pl) {  
  71.             var res = pl.data;  
  72.             $scope.StudentID = res.StudentID;  
  73.             $scope.Name = res.Name;  
  74.             $scope.Email = res.Email;  
  75.             $scope.Class = res.Class;  
  76.             $scope.EnrollYear = res.EnrollYear;  
  77.             $scope.City = res.City;  
  78.             $scope.Country = res.Country;  
  79.             $scope.OperType = 0;  
  80.         },  
  81.                   function (errorPl) {  
  82.                       console.log('Some Error in Getting Details', errorPl);  
  83.                   });  
  84.     }  
  85.   
  86.     //To Delete Record  
  87.     $scope.delete = function (Student) {  
  88.         var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);  
  89.         promiseDelete.then(function (pl) {  
  90.             $scope.Message = "Student Deleted Successfuly";  
  91.             GetAllRecords();  
  92.             ClearModels();  
  93.         }, function (err) {  
  94.             console.log("Some Error Occured." + err);  
  95.         });  
  96.     }  
  97. });  
3. Services.JS

Here change the WCF Service URL according to your WCF Service.
  1. /// <reference path="../angular.min.js" />  
  2. /// <reference path="Modules.js" />  
  3.   
  4. app.service("CRUD_AngularJs_RESTService"function ($http) {  
  5.     //Create new record  
  6.     this.post = function (Student) {  
  7.         var request = $http({  
  8.             method: "post",  
  9.             url: "http://localhost:27321/StudentService.svc/AddNewStudent",  
  10.             data: Student  
  11.         });  
  12.         return request;  
  13.     }  
  14.   
  15.     //Update the Record  
  16.     this.put = function (StudentID, Student) {  
  17.         debugger;  
  18.         var request = $http({  
  19.             method: "put",  
  20.             url: "http://localhost:27321/StudentService.svc/UpdateStudent",  
  21.             data: Student  
  22.         });  
  23.         return request;  
  24.     }  
  25.   
  26.     this.getAllStudent = function () {  
  27.         return $http.get("http://localhost:27321/StudentService.svc/GetAllStudent");  
  28.     };  
  29.   
  30.     //Get Single Records  
  31.     this.get = function (StudentID) {  
  32.         return $http.get("http://localhost:27321/StudentService.svc/GetStudentDetails/" + StudentID);  
  33.     }  
  34.   
  35.     //Delete the Record  
  36.     this.delete = function (StudentID) {  
  37.         var request = $http({  
  38.             method: "delete",  
  39.             url: "http://localhost:27321/StudentService.svc/DeleteStudent/" + StudentID  
  40.         });  
  41.         return request;  
  42.     }  
  43. });  
Now add a new controller as in the following:

Right-click on the Controller folder then select Add New.

add new controller
Image 21

controller name
Image 22

Now add a View.

Right-click on Index then select "Add View...".

add view
Image 23

type view name
Image 24

Now Index.cshtm will be:
  1. <html data-ng-app="RESTClientModule">  
  2. @{  
  3.     ViewBag.Title = "Manage Student Information using AngularJs, WCF REST & MVC4";  
  4. }  
  5.   
  6. <body>  
  7.     <table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">  
  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. <script src="~/Scripts/angular.js"></script>  
  129. <script src="~/Scripts/MyScripts/Modules.js"></script>  
  130. <script src="~/Scripts/MyScripts/Services.js"></script>  
  131. <script src="~/Scripts/MyScripts/Controllers.js"></script>  
It is now time to run the application. To run your view make the following changes in Route.config:

 

routes
Image 25

Now run application as in the following:

AngulaJS CRUD operation
Image 26

save data
Image 27

manage student
Image 28