CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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  =  ON )  ON  [ PRIMARY ]
  13. )  ON  [ PRIMARY ]
  14. GO
  15. SET  ANSI_PADDING  OFF
  16. 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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 2

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

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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:

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 5

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.Linq;
  4. using  System.Web;
  5. using  System.Runtime.Serialization;
  6. namespace  WCF_REST_Service
  7. {
  8. public   class  StudentDataContract
  9. {
  10. [DataContract]
  11. public   class  EmployeeDataContract
  12. {
  13. [DataMember]
  14. public   string  StudentID {  get ;  set ; }
  15. [DataMember]
  16. public   string  Name {  get ;  set ; }
  17. [DataMember]
  18. public   string  Email {  get ;  set ; }
  19. [DataMember]
  20. public   string  Class {  get ;  set ; }
  21. [DataMember]
  22. public   string  EnrollYear {  get ;  set ; }
  23. [DataMember]
  24. public   string  City {  get ;  set ; }
  25. [DataMember]
  26. public   string  Country {  get ;  set ; }
  27. }
  28. }
  29. }

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 6

Select the ADO.NET Entity Data Model.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 7

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 8

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

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 9

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 10

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 11

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 12

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

  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. namespace  WCF_REST_Service
  9. {
  10. public   class  StudentService : IStudentService
  11. {
  12. SchoolManagementEntities ctx;
  13. public  StudentService()
  14. {
  15. ctx =  new  SchoolManagementEntities();
  16. }
  17. public  List<StudentDataContract> GetAllStudent()
  18. {
  19. var query = (from a  in  ctx.Student
  20. select a).Distinct();
  21. List<StudentDataContract> studentList =  new  List<StudentDataContract>();
  22. query.ToList().ForEach(rec =>
  23. {
  24. studentList.Add( new  StudentDataContract
  25. {
  26. StudentID = Convert.ToString(rec.StudentID),
  27. Name = rec.Name,
  28. Email = rec.Email,
  29. EnrollYear = rec.EnrollYear,
  30. Class = rec.Class,
  31. City = rec.City,
  32. Country = rec.Country
  33. });
  34. });
  35. return  studentList;
  36. }
  37. public  StudentDataContract GetStudentDetails( string  StudentId)
  38. {
  39. StudentDataContract student =  new  StudentDataContract();
  40. try
  41. {
  42. int  Emp_ID = Convert.ToInt32(StudentId);
  43. var query = (from a  in  ctx.Student
  44. where a.StudentID.Equals(Emp_ID)
  45. select a).Distinct().FirstOrDefault();
  46. student.StudentID = Convert.ToString(query.StudentID);
  47. student.Name = query.Name;
  48. student.Email = query.Email;
  49. student.EnrollYear = query.EnrollYear;
  50. student.Class = query.Class;
  51. student.City = query.City;
  52. student.Country = query.Country;
  53. }
  54. catch  (Exception ex)
  55. {
  56. throw   new  FaultException< string >
  57. (ex.Message);
  58. }
  59. return  student;
  60. }
  61. public   bool  AddNewStudent(StudentDataContract student)
  62. {
  63. try
  64. {
  65. Student std = ctx.Student.Create();
  66. std.Name = student.Name;
  67. std.Email = student.Email;
  68. std.Class = student.Class;
  69. std.EnrollYear = student.EnrollYear;
  70. std.City = student.City;
  71. std.Country = student.Country;
  72. ctx.Student.Add(std);
  73. ctx.SaveChanges();
  74. }
  75. catch  (Exception ex)
  76. {
  77. throw   new  FaultException< string >
  78. (ex.Message);
  79. }
  80. return   true ;
  81. }
  82. public   void  UpdateStudent(StudentDataContract student)
  83. {
  84. try
  85. {
  86. int  Stud_Id = Convert.ToInt32(student.StudentID);
  87. Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
  88. std.Name = student.Name;
  89. std.Email = student.Email;
  90. std.Class = student.Class;
  91. std.EnrollYear = student.EnrollYear;
  92. std.City = student.City;
  93. std.Country = student.Country;
  94. ctx.SaveChanges();
  95. }
  96. catch  (Exception ex)
  97. {
  98. throw   new  FaultException< string >
  99. (ex.Message);
  100. }
  101. }
  102. public   void  DeleteStudent( string  StudentId)
  103. {
  104. try
  105. {
  106. int  Stud_Id = Convert.ToInt32(StudentId);
  107. Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
  108. ctx.Student.Remove(std);
  109. ctx.SaveChanges();
  110. }
  111. catch  (Exception ex)
  112. {
  113. throw   new  FaultException< string >
  114. (ex.Message);
  115. }
  116. }
  117. }
  118. }

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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:

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 14

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 15

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 17

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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.

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 19

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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. ( function  () {
  4. app = angular.module( "RESTClientModule" , []);
  5. })();

2. Controller.JS

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

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. app.service( "CRUD_AngularJs_RESTService" ,  function  ($http) {
  4. //Create new record
  5. this .post =  function  (Student) {
  6. var  request = $http({
  7. method:  "post" ,
  8. url:  "http://localhost:27321/StudentService.svc/AddNewStudent" ,
  9. data: Student
  10. });
  11. return  request;
  12. }
  13. //Update the Record
  14. this .put =  function  (StudentID, Student) {
  15. debugger ;
  16. var  request = $http({
  17. method:  "put" ,
  18. url:  "http://localhost:27321/StudentService.svc/UpdateStudent" ,
  19. data: Student
  20. });
  21. return  request;
  22. }
  23. this .getAllStudent =  function  () {
  24. return  $http.get( "http://localhost:27321/StudentService.svc/GetAllStudent" );
  25. };
  26. //Get Single Records
  27. this .get =  function  (StudentID) {
  28. return  $http.get( "http://localhost:27321/StudentService.svc/GetStudentDetails/"  + StudentID);
  29. }
  30. //Delete the Record
  31. this . delete  =  function  (StudentID) {
  32. var  request = $http({
  33. method:  "delete" ,
  34. url:  "http://localhost:27321/StudentService.svc/DeleteStudent/"  + StudentID
  35. });
  36. return  request;
  37. }
  38. });

Now add a new controller as in the following:

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

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 21

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 22

Now add a View.

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

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 23

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

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. <body>
  6. <table id= "tblContainer"  data-ng-controller= "CRUD_AngularJs_RESTController" >
  7. <tr>
  8. <td>
  9. <table style= "border: solid 2px Green; padding: 5px;" >
  10. <tr style= "height: 30px; background-color: skyblue; color: maroon;" >
  11. <th></th>
  12. <th>ID</th>
  13. <th>Name</th>
  14. <th>Email</th>
  15. <th>Class</th>
  16. <th>Year</th>
  17. <th>City</th>
  18. <th>Country</th>
  19. <th></th>
  20. <th></th>
  21. </tr>
  22. <tbody data-ng-repeat= "stud in Students" >
  23. <tr>
  24. <td></td>
  25. <td><span>{{stud.StudentID}}</span></td>
  26. <td><span>{{stud.Name}}</span></td>
  27. <td><span>{{stud.Email}}</span></td>
  28. <td><span>{{stud.Class}}</span></td>
  29. <td><span>{{stud.EnrollYear}}</span></td>
  30. <td><span>{{stud.City}}</span></td>
  31. <td><span>{{stud.Country}}</span></td>
  32. <td>
  33. <input type= "button"  id= "Edit"  value= "Edit"  data-ng-click= "get(stud)"  /></td>
  34. <td>
  35. <input type= "button"  id= "Delete"  value= "Delete"  data-ng-click= "delete(stud)"  /></td>
  36. </tr>
  37. </tbody>
  38. </table>
  39. </td>
  40. </tr>
  41. <tr>
  42. <td>
  43. <div style= "color: red;" >{{Message}}</div>
  44. <table style= "border: solid 4px Red; padding: 2px;" >
  45. <tr>
  46. <td></td>
  47. <td>
  48. <span>Student ID</span>
  49. </td>
  50. <td>
  51. <input type= "text"  id= "StudentID"  readonly= "readonly"  data-ng-model= "StudentID"  />
  52. </td>
  53. </tr>
  54. <tr>
  55. <td></td>
  56. <td>
  57. <span>Student Name</span>
  58. </td>
  59. <td>
  60. <input type= "text"  id= "sName"  required data-ng-model= "Name"  />
  61. </td>
  62. </tr>
  63. <tr>
  64. <td></td>
  65. <td>
  66. <span>Email</span>
  67. </td>
  68. <td>
  69. <input type= "text"  id= "sEmail"  required data-ng-model= "Email"  />
  70. </td>
  71. </tr>
  72. <tr>
  73. <td></td>
  74. <td>
  75. <span>Class</span>
  76. </td>
  77. <td>
  78. <input type= "text"  id= "sClass"  required data-ng-model= "Class"  />
  79. </td>
  80. </tr>
  81. <tr>
  82. <td></td>
  83. <td>
  84. <span>Enrollement Year</span>
  85. </td>
  86. <td>
  87. <input type= "text"  id= "sEnrollYear"  required data-ng-model= "EnrollYear"  />
  88. </td>
  89. </tr>
  90. <tr>
  91. <td></td>
  92. <td>
  93. <span>City</span>
  94. </td>
  95. <td>
  96. <input type= "text"  id= "sCity"  required data-ng-model= "City"  />
  97. </td>
  98. </tr>
  99. <tr>
  100. <td></td>
  101. <td>
  102. <span>Country</span>
  103. </td>
  104. <td>
  105. <input type= "text"  id= "sCountry"  required data-ng-model= "Country"  />
  106. </td>
  107. </tr>
  108. <tr>
  109. <td></td>
  110. <td></td>
  111. <td>
  112. <input type= "button"  id= "save"  value= "Save"  data-ng-click= "save()"  />
  113. <input type= "button"  id= "Clear"  value= "Clear"  data-ng-click= "clear()"  />
  114. </td>
  115. </tr>
  116. </table>
  117. </td>
  118. </tr>
  119. </table>
  120. </body>
  121. </html>
  122. <script src= "~/Scripts/angular.js" ></script>
  123. <script src= "~/Scripts/MyScripts/Modules.js" ></script>
  124. <script src= "~/Scripts/MyScripts/Services.js" ></script>
  125. <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: CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 25

Now run application as in the following:

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 26

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 27

CRUD Operations in MVC4 Using AngularJS and WCF REST Services

Image 28

上一篇:C#程序实现动态调用DLL的研究(转)


下一篇:C#程序实现动态调用DLL的研究[转]