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.

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.

Image 2

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

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.

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:

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.

Image 6

Select the ADO.NET Entity Data Model.

Image 7

Image 8

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

Image 9

Image 10

Image 11

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.

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:

Image 14

Image 15

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.

Image 17

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.

Image 19

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.

Image 21

Image 22

Now add a View.

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

Image 23

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:

Image 25

Now run application as in the following:

Image 26

Image 27

Image 28

CRUD Operations in MVC4 Using AngularJS and WCF REST Services的更多相关文章

  1. CRUD Operations In ASP.NET MVC 5 Using ADO.NET

    Background After awesome response of an published by me in the year 2013: Insert, Update, Delete In ...

  2. MongoDB - MongoDB CRUD Operations

    CRUD operations create, read, update, and delete documents. Create Operations Create or insert opera ...

  3. MyBatis Tutorial – CRUD Operations and Mapping Relationships – Part 1---- reference

    http://www.javacodegeeks.com/2012/11/mybatis-tutorial-crud-operations-and-mapping-relationships-part ...

  4. 【转载】Apache Jena TDB CRUD operations

    Apache Jena TDB CRUD operations June 11, 2015 by maltesander http://tutorial-academy.com/apache-jena ...

  5. [转]Enabling CRUD Operations in ASP.NET Web API 1

    本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...

  6. WCF RIA Services使用详解(转载)

    理解领域服务和领域操作 本文目录: 3.1 WCF Ria Services简介 3.1.1 什么是WCF Ria Services 3.1.2 WCF Ria Services如何生成客户端代码 3 ...

  7. [转]WCF Data Services OData

    http://martinwilley.com/net/data/wcfds.html WCF Data Services About OData Server code Client For .ne ...

  8. [转]Consuming a OData Service in a Client Application (WCF Data Services)

    本文转自:https://msdn.microsoft.com/zh-tw/library/dd728282(v=vs.103).aspx WCF Data Services 5.0   其他版本   ...

  9. 精进不休 .NET 4.5 (12) - ADO.NET Entity Framework 6.0 新特性, WCF Data Services 5.6 新特性

    [索引页][源码下载] 精进不休 .NET 4.5 (12) - ADO.NET Entity Framework 6.0 新特性, WCF Data Services 5.6 新特性 作者:weba ...

随机推荐

  1. Android对话框之Context

    代码就这么一段: new AlertDialog.Builder(getApplicationContext(),R.style.MyAlertDialogStyle) .setTitle(" ...

  2. Can't get WebApplicationContext object from ContextRegistry.GetContext(): Resource handler for the 'web' protocol is not defined

    I'm stucked in configuring my web.config file under a web forms project in order to get an instance ...

  3. Redis内存数据库在Exchange会议室的应用

    本文论述了现有Exchange会议室应用现状和不足之处,并详细介绍了Redis内存数据库在Exchange会议室的应用,并给出了一种高性能的应用架构及采用关键技术和关键实现过程,最终实现大幅改进系统性 ...

  4. C#多线程管理代码

    /// <summary> /// 多线程执行 /// </summary> public class MultiThreadingWorker { /// <summa ...

  5. Shader Overview

    Unity有三种形式的Shader: (1)Surface Shaders:对光照管线的高层抽象,受光照和影子效果影响的shader,使用Cg/HLSL语言编写:不进行light相关操作的shader ...

  6. JavaScript的学习--正则表达式

    今天用正则表达式的时候遇到了不少问题,就研究了一下,参考了不少博客,特此记录. 正则表达式的参数    参考 /i (忽略大小写)/g (全文查找出现的所有匹配字符)/m (多行查找)/gi(全文查找 ...

  7. 基于tiny4412的Linux内核移植 -- MMA7660驱动移植(九-2)

    作者信息 作者: 彭东林 邮箱:pengdonglin137@163.com QQ:405728433 平台简介 开发板:tiny4412ADK + S700 + 4GB Flash 要移植的内核版本 ...

  8. js时间对象格式化 format(转载)

    /** * 时间对象的格式化 */ Date.prototype.format = function(format){ /* * format="yyyy-MM-dd hh:mm:ss&qu ...

  9. 存储过程分页 Ado.Net分页 EF分页 满足90%以上

    存储过程分页: create proc PR_PagerDataByTop @pageIndex int, @pageSize int, @count int out as select top(@p ...

  10. Sprint第三个冲刺(第七天)

    项目基本上可以说完成了,只是还有些小bug要修复.