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:
- Create a Database. (SchoolManagement).
- Create a Table (Student).
- Create a WCF REST Service Application to do CRUD operations.
- Create a MVC 4 application and use AngularJs to consume WCF REST service.
- 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:
- CREATE TABLE [dbo].[Student](
- [StudentID] [ int ] IDENTITY(1,1) NOT NULL ,
- [ Name ] [ varchar ](50) NULL ,
- [Email] [ varchar ](500) NULL ,
- [Class] [ varchar ](50) NULL ,
- [EnrollYear] [ varchar ](50) NULL ,
- [City] [ varchar ](50) NULL ,
- [Country] [ varchar ](50) NULL ,
- CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
- (
- [StudentID] ASC
- ) WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ]
- ) ON [ PRIMARY ]
- GO
- SET ANSI_PADDING OFF
- 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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Runtime.Serialization;
- namespace WCF_REST_Service
- {
- public class StudentDataContract
- {
- [DataContract]
- public class EmployeeDataContract
- {
- [DataMember]
- public string StudentID { get ; set ; }
- [DataMember]
- public string Name { get ; set ; }
- [DataMember]
- public string Email { get ; set ; }
- [DataMember]
- public string Class { get ; set ; }
- [DataMember]
- public string EnrollYear { get ; set ; }
- [DataMember]
- public string City { get ; set ; }
- [DataMember]
- public string Country { get ; set ; }
- }
- }
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.Text;
- using WCF_REST_Service.Model;
- namespace WCF_REST_Service
- {
- public class StudentService : IStudentService
- {
- SchoolManagementEntities ctx;
- public StudentService()
- {
- ctx = new SchoolManagementEntities();
- }
- public List<StudentDataContract> GetAllStudent()
- {
- var query = (from a in ctx.Student
- select a).Distinct();
- List<StudentDataContract> studentList = new List<StudentDataContract>();
- query.ToList().ForEach(rec =>
- {
- studentList.Add( new StudentDataContract
- {
- StudentID = Convert.ToString(rec.StudentID),
- Name = rec.Name,
- Email = rec.Email,
- EnrollYear = rec.EnrollYear,
- Class = rec.Class,
- City = rec.City,
- Country = rec.Country
- });
- });
- return studentList;
- }
- public StudentDataContract GetStudentDetails( string StudentId)
- {
- StudentDataContract student = new StudentDataContract();
- try
- {
- int Emp_ID = Convert.ToInt32(StudentId);
- var query = (from a in ctx.Student
- where a.StudentID.Equals(Emp_ID)
- select a).Distinct().FirstOrDefault();
- student.StudentID = Convert.ToString(query.StudentID);
- student.Name = query.Name;
- student.Email = query.Email;
- student.EnrollYear = query.EnrollYear;
- student.Class = query.Class;
- student.City = query.City;
- student.Country = query.Country;
- }
- catch (Exception ex)
- {
- throw new FaultException< string >
- (ex.Message);
- }
- return student;
- }
- public bool AddNewStudent(StudentDataContract student)
- {
- try
- {
- Student std = ctx.Student.Create();
- std.Name = student.Name;
- std.Email = student.Email;
- std.Class = student.Class;
- std.EnrollYear = student.EnrollYear;
- std.City = student.City;
- std.Country = student.Country;
- ctx.Student.Add(std);
- ctx.SaveChanges();
- }
- catch (Exception ex)
- {
- throw new FaultException< string >
- (ex.Message);
- }
- return true ;
- }
- public void UpdateStudent(StudentDataContract student)
- {
- try
- {
- int Stud_Id = Convert.ToInt32(student.StudentID);
- Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
- std.Name = student.Name;
- std.Email = student.Email;
- std.Class = student.Class;
- std.EnrollYear = student.EnrollYear;
- std.City = student.City;
- std.Country = student.Country;
- ctx.SaveChanges();
- }
- catch (Exception ex)
- {
- throw new FaultException< string >
- (ex.Message);
- }
- }
- public void DeleteStudent( string StudentId)
- {
- try
- {
- int Stud_Id = Convert.ToInt32(StudentId);
- Student std = ctx.Student.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
- ctx.Student.Remove(std);
- ctx.SaveChanges();
- }
- catch (Exception ex)
- {
- throw new FaultException< string >
- (ex.Message);
- }
- }
- }
- }
Now make the following changes in your WCF application web.config file:
- <system.serviceModel>
- <behaviors>
- <serviceBehaviors>
- <behavior>
- <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
- <serviceMetadata httpGetEnabled= "true" httpsGetEnabled= "true" />
- <!-- 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 -->
- <serviceDebug includeExceptionDetailInFaults= "false" />
- </behavior>
- </serviceBehaviors>
- <endpointBehaviors>
- <behavior>
- <webHttp helpEnabled= "True" />
- </behavior>
- </endpointBehaviors>
- </behaviors>
- <protocolMapping>
- <add binding= "webHttpBinding" scheme= "http" />
- </protocolMapping>
- <serviceHostingEnvironment aspNetCompatibilityEnabled= "true" multipleSiteBindingsEnabled= "true" />
- </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:
- Modules.JS
- Controllers.JS
- Services.JS
1. Module.JS
- /// <reference path="../angular.min.js" />
- var app;
- ( function () {
- app = angular.module( "RESTClientModule" , []);
- })();
2. Controller.JS
- /// <reference path="../angular.min.js" />
- /// <reference path="Modules.js" />
- /// <reference path="Services.js" />
- app.controller( "CRUD_AngularJs_RESTController" , function ($scope, CRUD_AngularJs_RESTService) {
- $scope.OperType = 1;
- //1 Mean New Entry
- GetAllRecords();
- //To Get All Records
- function GetAllRecords() {
- var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
- promiseGet.then( function (pl) { $scope.Students = pl.data },
- function (errorPl) {
- $log.error( 'Some Error in Getting Records.' , errorPl);
- });
- }
- //To Clear all input controls.
- function ClearModels() {
- $scope.OperType = 1;
- $scope.StudentID = "" ;
- $scope.Name = "" ;
- $scope.Email = "" ;
- $scope.Class = "" ;
- $scope.EnrollYear = "" ;
- $scope.City = "" ;
- $scope.Country = "" ;
- }
- //To Create new record and Edit an existing Record.
- $scope.save = function () {
- var Student = {
- Name: $scope.Name,
- Email: $scope.Email,
- Class: $scope.Class,
- EnrollYear: $scope.EnrollYear,
- City: $scope.City,
- Country: $scope.Country
- };
- if ($scope.OperType === 1) {
- var promisePost = CRUD_AngularJs_RESTService.post(Student);
- promisePost.then( function (pl) {
- $scope.StudentID = pl.data.StudentID;
- GetAllRecords();
- ClearModels();
- }, function (err) {
- console.log( "Some error Occured" + err);
- });
- } else {
- //Edit the record
- debugger ;
- Student.StudentID = $scope.StudentID;
- var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
- promisePut.then( function (pl) {
- $scope.Message = "Student Updated Successfuly" ;
- GetAllRecords();
- ClearModels();
- }, function (err) {
- console.log( "Some Error Occured." + err);
- });
- }
- };
- //To Get Student Detail on the Base of Student ID
- $scope.get = function (Student) {
- var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
- promiseGetSingle.then( function (pl) {
- var res = pl.data;
- $scope.StudentID = res.StudentID;
- $scope.Name = res.Name;
- $scope.Email = res.Email;
- $scope.Class = res.Class;
- $scope.EnrollYear = res.EnrollYear;
- $scope.City = res.City;
- $scope.Country = res.Country;
- $scope.OperType = 0;
- },
- function (errorPl) {
- console.log( 'Some Error in Getting Details' , errorPl);
- });
- }
- //To Delete Record
- $scope. delete = function (Student) {
- var promiseDelete = CRUD_AngularJs_RESTService. delete (Student.StudentID);
- promiseDelete.then( function (pl) {
- $scope.Message = "Student Deleted Successfuly" ;
- GetAllRecords();
- ClearModels();
- }, function (err) {
- console.log( "Some Error Occured." + err);
- });
- }
- });
3. Services.JS
Here change the WCF Service URL according to your WCF Service.
- /// <reference path="../angular.min.js" />
- /// <reference path="Modules.js" />
- app.service( "CRUD_AngularJs_RESTService" , function ($http) {
- //Create new record
- this .post = function (Student) {
- var request = $http({
- method: "post" ,
- url: "http://localhost:27321/StudentService.svc/AddNewStudent" ,
- data: Student
- });
- return request;
- }
- //Update the Record
- this .put = function (StudentID, Student) {
- debugger ;
- var request = $http({
- method: "put" ,
- url: "http://localhost:27321/StudentService.svc/UpdateStudent" ,
- data: Student
- });
- return request;
- }
- this .getAllStudent = function () {
- return $http.get( "http://localhost:27321/StudentService.svc/GetAllStudent" );
- };
- //Get Single Records
- this .get = function (StudentID) {
- return $http.get( "http://localhost:27321/StudentService.svc/GetStudentDetails/" + StudentID);
- }
- //Delete the Record
- this . delete = function (StudentID) {
- var request = $http({
- method: "delete" ,
- url: "http://localhost:27321/StudentService.svc/DeleteStudent/" + StudentID
- });
- return request;
- }
- });
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:
- <html data-ng-app= "RESTClientModule" >
- @{
- ViewBag.Title = "Manage Student Information using AngularJs, WCF REST & MVC4" ;
- }
- <body>
- <table id= "tblContainer" data-ng-controller= "CRUD_AngularJs_RESTController" >
- <tr>
- <td>
- <table style= "border: solid 2px Green; padding: 5px;" >
- <tr style= "height: 30px; background-color: skyblue; color: maroon;" >
- <th></th>
- <th>ID</th>
- <th>Name</th>
- <th>Email</th>
- <th>Class</th>
- <th>Year</th>
- <th>City</th>
- <th>Country</th>
- <th></th>
- <th></th>
- </tr>
- <tbody data-ng-repeat= "stud in Students" >
- <tr>
- <td></td>
- <td><span>{{stud.StudentID}}</span></td>
- <td><span>{{stud.Name}}</span></td>
- <td><span>{{stud.Email}}</span></td>
- <td><span>{{stud.Class}}</span></td>
- <td><span>{{stud.EnrollYear}}</span></td>
- <td><span>{{stud.City}}</span></td>
- <td><span>{{stud.Country}}</span></td>
- <td>
- <input type= "button" id= "Edit" value= "Edit" data-ng-click= "get(stud)" /></td>
- <td>
- <input type= "button" id= "Delete" value= "Delete" data-ng-click= "delete(stud)" /></td>
- </tr>
- </tbody>
- </table>
- </td>
- </tr>
- <tr>
- <td>
- <div style= "color: red;" >{{Message}}</div>
- <table style= "border: solid 4px Red; padding: 2px;" >
- <tr>
- <td></td>
- <td>
- <span>Student ID</span>
- </td>
- <td>
- <input type= "text" id= "StudentID" readonly= "readonly" data-ng-model= "StudentID" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>Student Name</span>
- </td>
- <td>
- <input type= "text" id= "sName" required data-ng-model= "Name" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>Email</span>
- </td>
- <td>
- <input type= "text" id= "sEmail" required data-ng-model= "Email" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>Class</span>
- </td>
- <td>
- <input type= "text" id= "sClass" required data-ng-model= "Class" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>Enrollement Year</span>
- </td>
- <td>
- <input type= "text" id= "sEnrollYear" required data-ng-model= "EnrollYear" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>City</span>
- </td>
- <td>
- <input type= "text" id= "sCity" required data-ng-model= "City" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <span>Country</span>
- </td>
- <td>
- <input type= "text" id= "sCountry" required data-ng-model= "Country" />
- </td>
- </tr>
- <tr>
- <td></td>
- <td></td>
- <td>
- <input type= "button" id= "save" value= "Save" data-ng-click= "save()" />
- <input type= "button" id= "Clear" value= "Clear" data-ng-click= "clear()" />
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </body>
- </html>
- <script src= "~/Scripts/angular.js" ></script>
- <script src= "~/Scripts/MyScripts/Modules.js" ></script>
- <script src= "~/Scripts/MyScripts/Services.js" ></script>
- <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的更多相关文章
- 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 ...
- MongoDB - MongoDB CRUD Operations
CRUD operations create, read, update, and delete documents. Create Operations Create or insert opera ...
- MyBatis Tutorial – CRUD Operations and Mapping Relationships – Part 1---- reference
http://www.javacodegeeks.com/2012/11/mybatis-tutorial-crud-operations-and-mapping-relationships-part ...
- 【转载】Apache Jena TDB CRUD operations
Apache Jena TDB CRUD operations June 11, 2015 by maltesander http://tutorial-academy.com/apache-jena ...
- [转]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 ...
- WCF RIA Services使用详解(转载)
理解领域服务和领域操作 本文目录: 3.1 WCF Ria Services简介 3.1.1 什么是WCF Ria Services 3.1.2 WCF Ria Services如何生成客户端代码 3 ...
- [转]WCF Data Services OData
http://martinwilley.com/net/data/wcfds.html WCF Data Services About OData Server code Client For .ne ...
- [转]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 其他版本 ...
- 精进不休 .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 ...
随机推荐
- 在多线程环境中使用CoreData
在多线程环境中使用CoreData BY 子非鱼 · 2014 年 10 月 13 日 上回书说道,其实CoreData学起来也没有很复杂,我们其实增删改查都和别的ORM大同小异.但是世界总是很复 ...
- android html 与webview属性从冲突
在最近的项目开发中,使用webview加载html页面,这样可以节省大量页面开发的时间,同时也可加快项目进度. 我们需求是需要显示商品评论,页面设计如下: 调用android代码,对于webview的 ...
- 30分钟入门Java8之方法引用
30分钟入门Java8之方法引用 前言 之前两篇文章分别介绍了Java8的lambda表达式和默认方法和静态接口方法.今天我们继续学习Java8的新语言特性--方法引用(Method Referenc ...
- javacc学习
为什么要研究这些,除了个人兴趣之外,还有可以了解语言是怎样解析字符串生成逻辑代码. 他的应用性也是非常之广,如人工智能方面,把复杂的逻辑抽象成简单的文法,不懂编程的人都可以使用 说到人工智能,数据库S ...
- net组件转化成COM组件
第一步:生成秘钥文件 强名称工具 (Sn.exe) 有助于使用强名称对程序集进行签名.Sn.exe 提供了用于密钥管理.签名生成和签名验证的选项. 1.使用Visual Studio 命令 Visua ...
- [作业向]tinyhttp web服务器设计及完整代码
最近看了<HTTP权威指南>和<UNP>有了写一个简单的web服务器的想法,正好这个学期没有什么课,所以就花了一个星期这样写了一个出来,鉴于本人水平有限,如果有什么设计或代码错 ...
- ServiceStack.Redis 中关系操作的局限与bug
redis是文档型的,nosql中难处理的是关系. 比如人可以发博客,博客可以有分类.按照传统sql中,用户表和分类表都是主表,博客表是从表,有用户的外键和分类的外键 如果使用文档型的思考方式. 为用 ...
- JS设计模式1-单例模式
单例模式是一种常用的模式,有一些对象我们往往只需要一个,比如全局缓存,window对象.单例模式在js开发中单例模式的用途非常广泛,比如页面中有一个登录浮窗,无论单击多少次登录窗口,这个窗口只会创建一 ...
- 关于开发Windows服务程序容易搞混的地方!
在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...
- SQL Server技术问题之触发器优缺点
优点: 1.强化约束:强制复杂业务的规则和要求,能实现比check语句更为复杂的约束. 2.跟踪变化:触发器可以侦测数据库内的操作,从而禁止数据库中未经许可的更新和变化. 3.级联运行:侦测数据库内的 ...