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. unity3d 本地数据存储

    using UnityEngine; using System.Collections; //路径工具类 public class PathKit { /** 后缀常量字符 */ public con ...

  2. 二十九、EFW框架开发的系统支持SaaS模式和实现思路

    回<[开源]EFW框架系列文章索引>        EFW框架源代码下载V1.3:http://pan.baidu.com/s/1c0dADO0 EFW框架实例源代码下载:http://p ...

  3. MyBatis知多少(16)MyBatis映射

    之前我们详细地讨论了MyBatis背后的设计理念以及iBATIS框架是如何产生的.也说明了MyBatis是一个混合型解决方案,它从处理关系数据库的其他不同方法那里借鉴了许多思想.那么MyBatis到底 ...

  4. STL中的map/multimap小结

    (1)使用map/multimap之前必须包含头文件<map>:#include<map> 并且和所有的关联式容器一样,map/multimap通常以平衡二叉树来完成 (2)n ...

  5. 菜鸟学Windows Phone 8开发(3)——布局和事件基础

    本系列文章来源MSDN的 面向完全新手的 Windows Phone 8 开发  本文地址:http://channel9.msdn.com/Series/Windows-Phone-8-Develo ...

  6. eclipse开发web应用程序步骤(图解)

    *运行环境(也就是服务器的选择) 环境搭建好之后开始编写web程序!然后右键->Run as -> Run on Server!

  7. JS魔法堂:阻止元素被选中

    一.前言 在为IE5.5~9polyfill HTML5新特性placeholder时需要阻止元素被选中,因此在网上.书上查阅相关资料,记录在此以便日后查阅. 二.IE10+实现方式──CSS3 .u ...

  8. 网狐6603手机棋牌游戏源码.rar

    网狐6603手机棋牌游戏源码.rar   文件大小: 333 MB 发布一款手机棋牌游戏源码带教程文档! 仅供学习,下载后请务必在24小时内删除! 网狐6603手机棋牌游戏源码 链接:http://p ...

  9. Linq专题之Linq查询from子句

    Linq查询表达式包含8个常用的子句:from.where.select.join.into.orderby.group.let.我们来看看详细的说明.      from:      指定查询操作的 ...

  10. css 样式表

    CSS(cascading style sheets,层叠样式表),作用是美化HTML网页. /*注释*/   注释语法 2.1 样式表的基本概念 2.1.1样式表的分类 1.内联样式表 和HTML联 ...