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. 在多线程环境中使用CoreData

    在多线程环境中使用CoreData BY 子非鱼 · 2014 年 10 月 13 日   上回书说道,其实CoreData学起来也没有很复杂,我们其实增删改查都和别的ORM大同小异.但是世界总是很复 ...

  2. android html 与webview属性从冲突

    在最近的项目开发中,使用webview加载html页面,这样可以节省大量页面开发的时间,同时也可加快项目进度. 我们需求是需要显示商品评论,页面设计如下: 调用android代码,对于webview的 ...

  3. 30分钟入门Java8之方法引用

    30分钟入门Java8之方法引用 前言 之前两篇文章分别介绍了Java8的lambda表达式和默认方法和静态接口方法.今天我们继续学习Java8的新语言特性--方法引用(Method Referenc ...

  4. javacc学习

    为什么要研究这些,除了个人兴趣之外,还有可以了解语言是怎样解析字符串生成逻辑代码. 他的应用性也是非常之广,如人工智能方面,把复杂的逻辑抽象成简单的文法,不懂编程的人都可以使用 说到人工智能,数据库S ...

  5. net组件转化成COM组件

    第一步:生成秘钥文件 强名称工具 (Sn.exe) 有助于使用强名称对程序集进行签名.Sn.exe 提供了用于密钥管理.签名生成和签名验证的选项. 1.使用Visual Studio 命令 Visua ...

  6. [作业向]tinyhttp web服务器设计及完整代码

    最近看了<HTTP权威指南>和<UNP>有了写一个简单的web服务器的想法,正好这个学期没有什么课,所以就花了一个星期这样写了一个出来,鉴于本人水平有限,如果有什么设计或代码错 ...

  7. ServiceStack.Redis 中关系操作的局限与bug

    redis是文档型的,nosql中难处理的是关系. 比如人可以发博客,博客可以有分类.按照传统sql中,用户表和分类表都是主表,博客表是从表,有用户的外键和分类的外键 如果使用文档型的思考方式. 为用 ...

  8. JS设计模式1-单例模式

    单例模式是一种常用的模式,有一些对象我们往往只需要一个,比如全局缓存,window对象.单例模式在js开发中单例模式的用途非常广泛,比如页面中有一个登录浮窗,无论单击多少次登录窗口,这个窗口只会创建一 ...

  9. 关于开发Windows服务程序容易搞混的地方!

    在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...

  10. SQL Server技术问题之触发器优缺点

    优点: 1.强化约束:强制复杂业务的规则和要求,能实现比check语句更为复杂的约束. 2.跟踪变化:触发器可以侦测数据库内的操作,从而禁止数据库中未经许可的更新和变化. 3.级联运行:侦测数据库内的 ...