Send Object of Objects From AngularJS to WebAPI

Introduction

In this article I am explaining a really interesting and helpful thing, how to send an object of objects from AngularJs to WebAPI.

You might be making the calls from AngularJs to WebAPI or Web Service and you might encounter the situation where you need to send a large amount of data in the form of objects to your WebAPI. In that a case you can check this article and I am sure this will definitely help you.

Step 1

First of all I am creating a demo form with some HTML input controls.

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>  
  5.     <script src="JavaScript1.js"></script>  
  6. </head>  
  7.   
  8. <body ng-app>  
  9.     <hr />  
  10.     <h3>Send Objects of Objects Using AngularJS   
  11.     </h3>  
  12.     <hr />  
  13.     <div ng-controller="TestCtrl">  
  14.         <hr />  
  15.         <div>  
  16.             First Name:  
  17.             <input type="text" placeholder="Enter your name" ng-model="details.firstName">  
  18.             Last Name:  
  19.             <input type="text" placeholder="Enter your last name" ng-model="details.lastName">  
  20.         </div>  
  21.         <hr />  
  22.         <div>  
  23.             Mobile Number:              
  24.             <input type="text" placeholder="Enter your mobile number" ng-model="details.mobile">  
  25.             EmailId:  
  26.             <input type="text" placeholder="Enter your email id" ng-model="details.email">  
  27.         </div>  
  28.         <input type="button" ng-click="SendData(details)" value="Submit" />  
  29.         <hr />  
  30.         <h4 style="color:blueviolet">{{value}}</h4>  
  31.     </div>  
  32.     <hr />  
  33. </body>  
  34. </html>

Here I created four textboxes, a button and a h3 tag that will confirm that our data has reached the API.

You can see that I had bound a model to each input control in the form of "details.firstName". A really good and helpful feature of Angular is that if it doesn't find any model specified on the HTML page in the JavaScript code then it first creates and then binds the value of it. I am using this feature of Angular. Here the details are working like a parent model in which multiple modules exist, I am using this approach because in this way I just need to pass the "detail" to the function on the click of a button and in that function all the values would be retrieved easily using this parent model. On the click of the button a function is called named SendData, in this function all the values are sent by just sending the parent model.

Step 2

Now we need to write our Angular Code, so for that add a JavaScript file and write code, something like the following:

  1. var TestCtrl = function ($scope, $http) {  
  2.   
  3.     $scope.SendData = function (Data) {  
  4.         var GetAll = new Object();  
  5.         GetAll.FirstName = Data.firstName;  
  6.         GetAll.SecondName = Data.lastName;  
  7.         GetAll.SecondGet = new Object();  
  8.         GetAll.SecondGet.Mobile = Data.mobile;  
  9.         GetAll.SecondGet.EmailId = Data.email;  
  10.         $http({  
  11.             url: "NewRoute/firstCall",  
  12.             dataType: 'json',  
  13.             method: 'POST',  
  14.             data: GetAll,  
  15.             headers: {  
  16.                 "Content-Type""application/json"  
  17.             }  
  18.          }).success(function (response) {  
  19.             $scope.value = response;  
  20.          })  
  21.            .error(function (error) {  
  22.               alert(error);  
  23.            });  
  24.     }  
  25. }; 

Here you can see that we have created the controller with the name "TestCtrl", in this controller apart from $scope, $http is also written, that's because $http is the thing that makes the call in AngularJs.

In this controller I created a function, this is the same function that will be called on the click of the button. In the parameter the parent model is retrieved.

After this I created an object named "GetAll", this will work as the main object, in other words it will hold all other objects in it.

In this object I had added some properties that are getting the values from the "Data" parameter. Remember one thing, the naming convention for objects and properties should be proper because we will create some classes in the WebAPI that will have the same name as objects.

After providing some properties I had again created an object but this object will work as the property of the first object.

After this again some properties are created in this second object and they are also getting the values from our parameter.

After all this I created a $http call that will call our WebAPI method. You can see that in the data I had simply provided this object and the wonderful thing is that the WebAPI will receive this object without any kind of problem.

In the success function I had passed the response to a scope that is bound to the h3 tag available at the bottom of our HTML page.

Step 3

Final work is on the WebAPI, so add a WebAPI to your project and add code like this:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace WebApplication2.Controllers  
  9. {  
  10.     [RoutePrefix("NewRoute")]  
  11.     public class NewController : ApiController  
  12.     {  
  13.         public class GetAll  
  14.         {  
  15.             public string FirstName { getset; }  
  16.             public string SecondName { getset; }  
  17.             public SecondGet SecondGet;  
  18.         }  
  19.         public class SecondGet  
  20.         {  
  21.             public string Mobile { getset; }  
  22.             public string EmailId { getset; }  
  23.         }  
  24.         [Route("firstCall")]  
  25.         [HttpPost]  
  26.         public string firstCall(HttpRequestMessage request,   
  27.             [FromBody] GetAll getAll)  
  28.         {  
  29.             return "Data Reached";  
  30.         }  
  31.     }  

Here first I created two classes and created some properties in these classes, you can see that I provided the same name to these classes that was provided when creating the objects on the JavaScript page.

The property name should also be same otherwise the data sent will not be mapped properly.

I used the second class as a property in the first class.

After creating the classes I created the HttpPost method and named it "firstCall". In this method I had HttpRequestMessage as the parameter because your method will not receive any kind of data from your Ajax call until and unless you allow your method by writing HttpRequestMessage. Since we are making the HttpPost call and we are sending a large amount of data from Angular we need to access that using the [FromBody], if we would be passing any kind of small data like any integer or string then we can use FromURI.

Since the data will reach here, it will send some message in return and that message can be seen in the h3 tag on the HTML page.

Now let's run the application and see the output.

Output

On running the application you will see a page with four fields and a button.

SendObjectOfObjectsUsingAngularJS

Fill in your data and click on the button, you can check the data in the console by putting a debugger in the JavaScript code.

SendObjectOfObjectsUsingAngularJS

 

SendObjectOfObjectsUsingAngularJS

Now if you add a debugger at the API also, then you can see that the data is assigned to the properties created in the classes.

SendObjectOfObjectsUsingAngularJS

The confirmation message can be seen in the browser.

SendObjectOfObjectsUsingAngularJS

Up Next
    Ebook Download
    View all
    Learn
    View all