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. CLR via C#深解笔记三 - 基元类型、引用类型和值类型 | 类型和成员基础 | 常量和字段

    编程语言的基元类型   某些数据类型如此常用,以至于许多编译器允许代码以简化的语法来操纵它们. System.Int32 a = new System.Int32();  // a = 0 a = 1 ...

  2. JavaScript高级之词法作用域和作用域链

    主要内容: 分析JavaScript的词法作用域的含义 解析变量的作用域链 变量名提升时什么 一.关于块级作用域         说到JavaScript的变量作用域,与咱们平时使用的类C语言不同. ...

  3. 【PRML读书笔记-Chapter1-Introduction】1.6 Information Theory

    熵 给定一个离散变量,我们观察它的每一个取值所包含的信息量的大小,因此,我们用来表示信息量的大小,概率分布为.当p(x)=1时,说明这个事件一定会发生,因此,它带给我的信息为0.(因为一定会发生,毫无 ...

  4. SNF开发平台WinForm之五-高级查询使用说明-SNF快速开发平台3.3-Spring.Net.Framework

    5.1运行效果: 5.2开发实现: 1.按上面效果来说,先来看一下在程序当中如果调用.第一步在页面拖拽一个按钮为“高级查询”,事件上写下如下代码: 如果是单表查询的话,只需要传GridView就行,如 ...

  5. 移动WEB开发中媒体查询里的width, device-width, resolution

    /*1.width: viewport的宽度,css像素,三星S3的viewort默认宽度是980px. 当设置viewport width=device-width时,对应的媒体查询中width的值 ...

  6. Unity 资源管理与更新

    当你在 工程目录下的 Asset 文件夹中放置一个文件时(电脑上的文件夹,不是 Unity 界面中的文件夹),Unity会自动检测到一个新的文件被添加(Unity会不停地检查Assets文件夹中的内容 ...

  7. 编写高质量JS代码的68个有效方法(五)

    No.21.使用apply方法通过不同数量的参数调用函数 Tips: 使用apply方法自定一个可计算的参数数组来调用可变参数的函数 使用apply方法的第一个参数给可变参数的方法提供一个接收者 // ...

  8. NOP登录验证管理

    截取Nop登录代码如下: 其实 public ActionResult Login(LoginModel model, string returnUrl, bool captchaValid) { / ...

  9. 伸展树(一)之 图文解析 和 C语言的实现

    概要 本章介绍伸展树.它和"二叉查找树"和"AVL树"一样,都是特殊的二叉树.在了解了"二叉查找树"和"AVL树"之后, ...

  10. Tools - Notepad++

    NotePad++ https://notepad-plus-plus.org/ 修改主题 依次点击设置---语言格式设置---选择主题,在显示界面中修改相关设置(背景色.前景色.字体等). 双文本横 ...