Web API With AngularJS

In this article we will learn about CRUD operations in Web API using AngularJS. We will use Visual Studio 2015 to create a Web API and perform the operation. In this project we are going to create a database and a table called tbl_Subcribers which actually contains a list of data. Here we will use Angular JS for all of our client side operations. If you are new to Web API, please read how to retrieve the data from database using Web API here. I am going to explain the complete process in a step by step manner. I hope you will like this.

Download the source code

You can always download the source code here: Web API and Angular JS


Yesterday, I got a call from one of my followers. He asked me about Web API, I explained to him all the things I know about the Web API. But he was not convinced with the information I shared through the phone. At last he asked me to write an article about Web API in a simple manner. So I agreed to do so. Here I am dedicating this article to him. I hope he will find this useful.

What is a Web API?

A Web API is a kind of a framework which makes building HTTP services easier than ever. It can be used almost everywhere including a wide range of clients, mobile devices, browsers, etc. It contains normal MVC features like Model, Controller, Actions, Routing, etc. It supports all HTTP verbs like POST, GET, DELETE, PUT.

Why Web API

Figure: Why Web API

Image Courtesy : blogs.msdn.com

Why Web API
Figure: Image Courtesy : forums.asp.net

Using the code

We will create our project in Visual Studio 2015. To create a project click File, New, then Project. And select Web API as template.

Web API Template

Figure: Web API Template

Once you have created a new project, your solution explorer will look like this.

Web API With Angular JS Solution Explorer

Figure: Web API with Angular JS Solution Explorer

As I said, we are going to use AngularJS for our client side operations. So the next thing we need to do is, installing the AngularJS from NuGet packages.

Installing Angular JS

Figure: Installing AngularJS

Install AngularJS

Now we will create a control in our project.


Figure: CRUD_in_MVC_Using_Web_API_Adding_Control

Now will create a database. Here I am using SQL Server Management Studio with SQL Server Express.

Create Database

The following is the query to create a database.

  1. USE [master]  
  2. GO  
  3. /****** Object: Database [SibeeshPassion] Script Date: 06-02-2016 08:18:42 PM ******/  
  4. CREATE DATABASE [SibeeshPassion]  
  7. NAME = N'SibeeshPassion', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\SibeeshPassion.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  8. LOG ON  
  9. NAME = N'SibeeshPassion_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\SibeeshPassion_log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC [SibeeshPassion].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  19. GO  
  21. GO  
  23. GO  
  25. GO  
  27. GO  
  29. GO  
  31. GO  
  33. GO  
  35. GO  
  37. GO  
  39. GO  
  41. GO  
  43. GO  
  45. GO  
  47. GO  
  49. GO  
  51. GO  
  53. GO  
  55. GO  
  57. GO  
  59. GO  
  61. GO  
  63. GO  
  64. ALTER DATABASE [SibeeshPassion] SET MULTI_USER  
  65. GO  
  67. GO  
  69. GO  
  71. GO  
  73. GO  
  75. GO  
  76. ALTER DATABASE [SibeeshPassion] SET READ_WRITE  
  77. GO   

Now we can create a table and insert data into it.

Create table in database

The following is the query to create table in database.

  1. USE [SibeeshPassion]  
  2. GO  
  3. /****** Object: Table [dbo].[tbl_Subscribers] Script Date: 06-02-2016 08:21:06 PM ******/  
  5. GO  
  7. GO  
  8. CREATE TABLE [dbo].[tbl_Subscribers](  
  9. [SubscriberID] [intNOT NULL,  
  10. [MailID] [nvarchar](50) NOT NULL,  
  11. [SubscribedDate] [datetime2](7) NOT NULL,  
  13. (  
  14. [SubscriberID] ASC  
  16. ON [PRIMARY]  
  17. GO   

Insert data to table

  1. INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (1, N'[email protected]', N'2015-10-30 00:00:00')  
  2. INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (2, N'[email protected]', N'2015-10-29 00:00:00')  
  3. INSERT INTO [dbo].[tbl_Subscribers] ([SubscriberID], [MailID], [SubscribedDate]) VALUES (3, N'[email protected]', N'2015-10-28 00:00:00')   

Our database seems to be ready now. Then we can go ahead and create entity in our project.

Creating entity model

To create an entity, please follow the steps as in the following images:

Creating Entity Model 1

Figure: Creating Entity Model 1

Creating Entity Model 2

Figure: Creating Entity Model 2

Creating Entity Model 3

Figure: Creating Entity Model 3

Creating Entity Model 4

Figure: Creating Entity Model 4

Creating Entity Model 5

Figure: Creating Entity Model 5

Creating Entity Model 6

Figure: Creating Entity Model 6

Now the time to create an API controller.

Select Empty API Controller as template.

Web API Contoller With Actions

Figure: Web API Controller With Actions

Read Operation

Now you can see some actions are already created for you by default. Cool, right? Now, as of now we will concentrate only on retrieving the data. So please change the method Get as follows.

  1. public IEnumerable<tbl_Subscribers> Get()  
  2. {  
  3.    return myEntity.tbl_Subscribers.AsEnumerable();  
  4. }   

Before that please do not forget to create an instance for your entity.

  1. private SibeeshPassionEntities myEntity = new SibeeshPassionEntities();   

And make sure you have added the needed namespaces with the model.

  1. using System.Data.Entity;  
  2. using WebAPIAndAngular.Models;   

As you can notice that we have selected Empty API Controller instead of selecting a normal controller. There are a few differences between our normal controller and Empty API Controller.

Controller VS Empty API Controller

A controller normally render your views. But an API controller returns the data which is already serialized. A controller action returns JSON() by converting the data. You can get rid of this using API controller.

Find out more: Controller VS API Controller

Now our API is ready for action. So it is time to create another controller and a view. Here I am creating a normal controller with Index view.

Once the view is created, we will created three JS files in the script folder.

Angular JS Operation FIles

Figure: AngularJS Operation FIles

Now we will start our AngularJS part.

Open the file Module.js and create an app.

  1. var app;  
  2. (function ()  
  3. {  
  4.     app = angular.module("APIModule", []);  
  5. })();   

Here APIModule is the name of our module. Check here for more information.

Open the file Service.js and create a service as follows.

  1. app.service("APIService", function ($http)  
  2. {  
  3.     this.getSubs = function ()  
  4.     {  
  5.         return $http.get("api/Subscriber")  
  6.     }  
  7. });   
Here, APIService is our service name which we will call from our controller. The api/Subscriber will call the Get method in our API controller.

Get Operation In API Controller

Figure: Get Operation In API Controller

Now open  Controller.JS and write the following code:

  1. app.controller('APIController', function ($scope, APIService)  
  2. {  
  3.     getAll();  
  5.     function getAll()  
  6.     {  
  7.         var servCall = APIService.getSubs();  
  8.         servCall.then(function (d)  
  9.         {  
  10.             $scope.subscriber = d.data;  
  11.         }, function (error)  
  12.         {  
  13.             $log.error('Oops! Something went wrong while fetching the data.')  
  14.         })  
  15.     }  
  16. })   

We are calling the getSubs function which we created in our service. Once we get the data we are assigning it to the $scope.subscriber, so that we can use it in our view.

Now the AngularJS part for retrieving all data is done. Can we do the needed changes in the view now?

Updating View

Open the Index.cshtml view and change it as below.

  1. @{  
  2. ViewBag.Title = "Welcome";  
  3. }  
  5. <style>  
  6. table, tr, td, th {  
  7. border: 1px solid #ccc;  
  8. padding: 10px;  
  9. margin: 10px;  
  10. }  
  11. </style>  
  12. <h2>Welcome to Sibeesh Passion's Email List</h2>  
  13. <body data-ng-app="APIModule">  
  14.     <div id="tblSubs" ng-controller="APIController">  
  15.         <table>  
  16.             <tr>  
  17.                 <th>ID</th>  
  18.                 <th>Email ID</th>  
  19.                 <th>Subscribed Date</th>  
  20.             </tr>  
  21.             <tbody data-ng-repeat="sub in subscriber">  
  22.                 <tr>  
  23.                     <td>{{sub.SubscriberID}}</td>  
  24.                     <td>{{sub.MailID}}</td>  
  25.                     <td>{{sub.SubscribedDate}}</td>  
  26.                 </tr>  
  27.             </tbody>  
  28.         </table>  
  29.     </div>  
  30. </body>  
  31. <script src="~/Scripts/angular.js"></script>  
  32. <script src="~/Scripts/angular-route.js"></script>  
  33. <script src="~/Scripts/APIScripts/Module.js"></script>  
  34. <script src="~/Scripts/APIScripts/Service.js"></script>  
  35. <script src="~/Scripts/APIScripts/Controller.js"></script>   

Please don’t forget to load the needed scripts. Here we have set body as our data-ng-app and table as our ng-controller. We are looping through the data using data-ng-repeat.

If everything is done, we can build the application and see the output.


Figure: Wep API Get All Record

So far our READ operation is done. Now we will move into CREATE part.

Create Operation

Firstly, we will concentrate on the view part as of now. Just add the following code to your view.

  1. <div class="form-group">  
  2.    <label for="email">Sbscribe here</label>  
  3.    <input type="email" class="form-control" id="email" placeholder="Enter email" [required="string" ] data-ng-model="mailid" />  
  4. </div>  
  5. <button type="button" class="btn btn-default" data-ng-click="saveSubs();">Submit</button>   

This will give you an output as follows.

View Design For Create

View Design For Create

As you can see, we are firing the function saveSubs() in data-ng-click. So let us see what we need to write in it.

In the Controller.js you need to create a function as below.

  1. $scope.saveSubs = function ()  
  2. {  
  3.     var sub = {  
  4.         MailID: $scope.mailid,  
  5.         SubscribedDate: new Date()  
  6.     };  
  7.     var saveSubs = APIService.saveSubscriber(sub);  
  8.     saveSubs.then(function (d)  
  9.     {  
  10.         getAll();  
  11.     }, function (error)  
  12.     {  
  13.         console.log('Oops! Something went wrong while saving the data.')  
  14.     })  
  15. };   

Did you saw that we are calling another function which is in our APIService? So now we need to create a function saveSubscriber in Service.js.

  1. this.saveSubscriber = function (sub)  
  2. {  
  3.     return $http(  
  4.     {  
  5.         method: 'post',  
  6.         data: sub,  
  7.         url: 'api/Subscriber'  
  8.     });  
  9. }   

So all set, the rest is to create a function in our API Controller.

  1. // POST: api/Subscriber  
  2. public void Post(tbl_Subscribers sub)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         myEntity.tbl_Subscribers.Add(sub);  
  7.         myEntity.SaveChanges();  
  8.     }  
  9. }   

That’s cool, now you will be able to create data through our API with the help of AngularJS. Now we shall  move into UPDATE operation.

Update Operation

Before going to the code part we will do some changes in our table design. We are going to make one field (Mail ID field) editable whenever the user double clicks on it. And of course we will update the edited data to the database whenever user leaves that field. Sounds cool, right? Now please change the view as follows.

  1. <div id="tblSubs" ng-controller="APIController">  
  2.     <table>  
  3.         <tr>  
  4.             <th>ID</th>  
  5.             <th>Email ID ( Double click to update)</th>  
  6.             <th>Subscribed Date</th>  
  7.             <th></th>  
  8.         </tr>  
  9.         <tbody data-ng-repeat="sub in subscriber">  
  10.             <tr>  
  11.                 <td>{{sub.SubscriberID}}</td>  
  12.                 <td ng-blur="updSubscriber(sub,$event)" ng-dblclick="makeEditable($event)">{{sub.MailID}}</td>  
  13.                 <td>{{sub.SubscribedDate}}</td>  
  14.             </tr>  
  15.         </tbody>  
  16.     </table>  
  17.     <div class="form-group"> <label for="email">Sbscribe here</label> <input type="email" class="form-control" id="email" placeholder="Enter email" [required="string" ] data-ng-model="mailid" /> </div> <button type="button" class="btn btn-default" data-ng-click="saveSubs();">Submit</button>   
  18.      </div>   

The below is the main change we did.

  1. <td ng-blur="updSubscriber(sub,$event)" ng-dblclick="makeEditable($event)">{{sub.MailID}}</td>   

In ng-blur we are calling the function updSubscriber with parameter $event and the current subscriber details. And in ng-dblclick we are calling the function makeEditable with parameter $event which actually holds the UI details and current events.

The following is the code for the function makeEditable in Controller.js,

  1. $scope.makeEditable = function (obj)  
  2. {  
  3.     obj.target.setAttribute("contenteditable"true);  
  4.     obj.target.focus();  
  5. };   

As you can see we are setting the attribute contenteditable to true using setAttribute function. Now we will look into the function updSubscriber.

Add a function in Controller.js

  1. $scope.updSubscriber = function (sub, eve)  
  2. {  
  3.     sub.MailID = eve.currentTarget.innerText;  
  4.     var upd = APIService.updateSubscriber(sub);  
  5.     upd.then(function (d)  
  6.     {  
  7.         getAll();  
  8.     }, function (error)  
  9.     {  
  10.         console.log('Oops! Something went wrong while updating the data.')  
  11.     })  
  12. };   

Add a relative function in Service.js

  1. this.updateSubscriber = function (sub)  
  2. {  
  3.     return $http(  
  4.     {  
  5.         method: 'put',  
  6.         data: sub,  
  7.         url: 'api/Subscriber'  
  8.     });  
  9. }   

Now we need to add a function in our Web API controller.

  1. // PUT: api/Subscriber/5  
  2. public void Put(tbl_Subscribers sub)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         myEntity.Entry(sub).State = EntityState.Modified;  
  7.         try  
  8.         {  
  9.             myEntity.SaveChanges();  
  10.         }  
  11.         catch (Exception)  
  12.         {  
  13.             throw;  
  14.         }  
  15.     }  
  16. }   

Now you will be able to update your record. What is pending now? Yes, DELETE operation.

Delete Operation

Make some changes in the view as follows.

  1. <tbody data-ng-repeat="sub in subscriber">  
  2.     <tr>  
  3.         <td>{{sub.SubscriberID}}</td>  
  4.         <td ng-blur="updSubscriber(sub,$event)" ng-dblclick="makeEditable($event)">{{sub.MailID}}</td>  
  5.         <td>{{sub.SubscribedDate}}</td>  
  6.         <td> <input type="button" id="Delete" value="Delete" data-ng-click="dltSubscriber(sub.SubscriberID)" /> </td>  
  7.     </tr>  
  8. </tbody>   

Now add the new function in Controller.js

  1. $scope.dltSubscriber = function (subID)  
  2. {  
  3.     var dlt = APIService.deleteSubscriber(subID);  
  4.     dlt.then(function (d)  
  5.     {  
  6.         getAll();  
  7.     }, function (error)  
  8.     {  
  9.         console.log('Oops! Something went wrong while deleting the data.')  
  10.     })  
  11. };   

Create a service in Service.js now.

  1. this.deleteSubscriber = function (subID)  
  2. {  
  3.     var url = 'api/Subscriber/' + subID;  
  4.     return $http(  
  5.     {  
  6.         method: 'delete',  
  7.         data: subID,  
  8.         url: url  
  9.     });  
  10. }  

Now it is time to create our delete method in Web API controller.

  1. // DELETE: api/Subscriber/5  
  2. public void Delete(int id)  
  3. {  
  4.     tbl_Subscribers dlt = myEntity.tbl_Subscribers.Find(id);  
  5.     if (dlt != null)  
  6.     {  
  7.         try  
  8.         {  
  9.             myEntity.tbl_Subscribers.Remove(dlt);  
  10.             myEntity.SaveChanges();  
  11.         }  
  12.         catch (Exception)  
  13.         {  
  14.             throw;  
  15.         }  
  16.     }  
  17. }   

That is all. We did it. Now build your application and you can see the following output:

Web API With Angular JS
Figure: Web API With Angular JS

Happy coding.


Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Did  you find this post useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

Please see this article in my blog here.

Read more articles on AngularJS: