Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

CRUD Operation in MVC 4 using AngularJs and WCF REST Service

Article:
Viewed:  7584 
Posted On:  21/11/2014 10:03:02 
How we can perform CRUD operations in MVC using AngularJs with WCF REST Services ? 

In my previous article I showed how can perform CRUD operation in MVC4 using AngularJs and WEB API.

Manage Data (CRUD operations) using MVC4 Web API AngularJs

Now in this article I am going to show how we can perform CRUD operation in MVC4 using AngularJs and WCF REST Services.

Highlight of Article:

  1. Create a Data Base. (SchoolManagement)
  2. Create  a Table (Student)
  3. Create a WCF REST Service Application to perform CRUD operations.
  4. Create a MVC 4 application and use AngularJs to consume WCF REST service.
  5. Perform CRUD (Create, Read, Update & Delete) Operations.

What is 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.

What is REST?

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 CRUD operations. i.e. Create, Retrieve, Update and Delete. 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:

Below is My Data Table.

1.png

Image 1.

Script of My Data Table is:

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
 

Now Create a new WCF REST Service. So follow below steps:

Open Visual Studio -> New -> Project -> Select WCF left Side -> Select WCF Service Application -> OK

2.png 

Image 2.

 

Now delete IService.cs and Service.cs files.

 3.png

Image 3.

 

Now Right click on Solution Explorer -> Add New Item -> Select WCF Service -> Name it as EmployeeService.

 

 4.png


Image 4.

 

Now I am going to create a Data Contract as StudentDataContract .

Right click on Solution Explorer -> Add New Item -> Add a .cs file and do below code:

 

 5.png


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 { getset; }
 
            [DataMember]
            public string Name { getset; }
 
            [DataMember]
            public string Email { getset; }
 
            [DataMember]
            public string Class { getset; }
 
            [DataMember]
            public string EnrollYear { getset; }
 
            [DataMember]
            public string City { getset; }
 
            [DataMember]
            public string Country { getset; }
        }
 
    }
}
 
Now time to add your Data Base to your application. So create a new folder name as Model in your project. Now Right Click on Model folder -> Add -> New Item


6.png 

Image 6.

 

Select ADO.NET Entity Data Model.

 

 7.png


Image 7.

 

 8.png


Image 8.

 

Here Click on New Connection -> Enter your SQL Server Details-> Select Your Data Base.

 

9.png 


Image 9.

 

 10.png


Image 10.

 

 11.png


Image 11.

 

 12.png


Image 12.

  

 Now open IStudentService.cs to define Interface.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
namespace WCF_REST_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IStudentService" in both code and config file together.
    [ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetAllStudent/")]
        List<StudentDataContract> GetAllStudent();
 
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetStudentDetails/{StudentId}")]
        StudentDataContract GetStudentDetails(string StudentId);
 
        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
             UriTemplate = "/AddNewStudent")]
        bool AddNewStudent(StudentDataContract student);
 
        [OperationContract]
        [WebInvoke(Method = "PUT",           
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/UpdateStudent")]
        void UpdateStudent(StudentDataContract contact);
 
        [OperationContract]
        [WebInvoke(Method = "DELETE",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "DeleteStudent/{StudentId}")]
        void DeleteStudent(string StudentId);
    }
}
 
 
Now Open StudentService.cs

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
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select StudentService.svc or StudentService.svc.cs at the Solution Explorer and
start debugging.
    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 changes in your WCF application web.config file as below:

<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 WCF REST service.

13.png

Image 13.
 
Now time to create a New MVC application. So right click on your solution and add new project as below:

 

 14.png


Image 14.

 

 15.png

Image 15.


 16.png


Image 16.

 

Now Add Your WCF Service URL in your MVC application. You can host your WCF service  in IIS or you can run it and discover the URL locally like below.

 

Right Click on your MVC project -> Add Service Reference.

 

 17.png


Image 17.

 

 18.png


Image 18.

 

Now Time to add AngularJs reference. So Right Click on your MVC project name in solution explorer -> Add NuGet Packages


 19.png

 

Image 19.

 20.png

 

Image 20.

 

Now create a New Folder (MyScripts) under Scripts Folder-> Here add 3 js files.

  1.    Modules.js
  2.    Controllers.js
  3.    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" + 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." + 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." + err);
        });
    }
});
 
 

3.    Services.js

Here change the WCF Service URL according 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:

Right click on Controller folder-> Add -> Controller

21.png

Image 21.

22.png

Image 22.

Now add a View.

Right click on Index -> Add-> View.

23.png 

Image 23.

24.png

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="bordersolid 2px Greenpadding5px;">
                    <tr style="height30pxbackground-colorskybluecolormaroon;">
                        <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="colorred;">{{Message}}</div>
                <table style="bordersolid 4px Redpadding2px;">
                    <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>
 
Now time to run the application. To run your view make changes in Route.config like below:

25.png

Image 25.

Now run application.

26.png

Image 26.

27.png

Image 27.

 28.png

Image 28.

  Comment:
 
By Kunal  On  07/07/2016 23:38:56
Hello Sir, I have used your Code so i have got the bellow error so please check and give me the answer.. XMLHttpRequest cannot load http://localhost:1876/StudentService.svc/GetAllStudent. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2768' is therefore not allowed access.
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us