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.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
- <script src="JavaScript1.js"></script>
- </head>
-
- <body ng-app>
- <hr />
- <h3>Send Objects of Objects Using AngularJS
- </h3>
- <hr />
- <div ng-controller="TestCtrl">
- <hr />
- <div>
- First Name:
- <input type="text" placeholder="Enter your name" ng-model="details.firstName">
- Last Name:
- <input type="text" placeholder="Enter your last name" ng-model="details.lastName">
- </div>
- <hr />
- <div>
- Mobile Number:
- <input type="text" placeholder="Enter your mobile number" ng-model="details.mobile">
- EmailId:
- <input type="text" placeholder="Enter your email id" ng-model="details.email">
- </div>
- <input type="button" ng-click="SendData(details)" value="Submit" />
- <hr />
- <h4 style="color:blueviolet">{{value}}</h4>
- </div>
- <hr />
- </body>
- </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:
- var TestCtrl = function ($scope, $http) {
-
- $scope.SendData = function (Data) {
- var GetAll = new Object();
- GetAll.FirstName = Data.firstName;
- GetAll.SecondName = Data.lastName;
- GetAll.SecondGet = new Object();
- GetAll.SecondGet.Mobile = Data.mobile;
- GetAll.SecondGet.EmailId = Data.email;
- $http({
- url: "NewRoute/firstCall",
- dataType: 'json',
- method: 'POST',
- data: GetAll,
- headers: {
- "Content-Type": "application/json"
- }
- }).success(function (response) {
- $scope.value = response;
- })
- .error(function (error) {
- alert(error);
- });
- }
- };
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
-
- namespace WebApplication2.Controllers
- {
- [RoutePrefix("NewRoute")]
- public class NewController : ApiController
- {
- public class GetAll
- {
- public string FirstName { get; set; }
- public string SecondName { get; set; }
- public SecondGet SecondGet;
- }
- public class SecondGet
- {
- public string Mobile { get; set; }
- public string EmailId { get; set; }
- }
- [Route("firstCall")]
- [HttpPost]
- public string firstCall(HttpRequestMessage request,
- [FromBody] GetAll getAll)
- {
- return "Data Reached";
- }
- }
- }
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.
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.
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.
The confirmation message can be seen in the browser.