Receiving AngularJS $http.post data using Request.Form in asp.net

Sheonarayan
Posted by in AngularJS category on for Advance level | Points: 250 | Views : 27838 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article, we shall learn how to send asynchronous POST request to the server using AngularJS and how retrieve send data on the server.
Recommendation
Read Using Angular $http.put with ASP.NET MVC project before this article.

Introduction

AngularJS has $http service that is used to send asynchronous request to the server. $http service has many shortcut methods for different types of request we want to send. For example
  1. $http.get
  2. $http.post
  3. $http.put
etc.

All works fine until we try $http.post method as this is little tricky. After searching internet, normally we find following ind of questions
  • $http.post returns null on the server
  • $http.post doesn't send form data on the server
  • $http:post sends null data on the server

It took more than an hour to find how to retrieve $http.post sent data to the server using Request.Form["keyName"] as we normally retrieve HTML form data on the server in ASP.NET / ASP.NET MVC.

Sending POST request using AngularJS $http.post


$http.post method accepts following parameters
  1. url - url to send request to
  2. data - data to send along with request
  3. config - configuration to use while sending request.
Once the request is successful, the success() method fires if not error() method fires. Both has 4 parameters

  1. data - data returned from the server
  2. status - status of the request
  3. headers - header information returned from the server
  4. config - configuration returned from the server
We mostly use only 1st and 2nd parameters to get the response from the server and know the status respectively.

Plug-ins required to run this 

  1. jquery.js - we need to have jQuery file referenced in the page
  2. angular.js - we need to have angular.js file referenced in the page

AngularJS HTML Form

In HTML form below, we have used the ng-app, ng-controller declared in the <script> block of the page. Three text boxes are using firstName, lastName and age as their ng-model. On Submit button click, the form gets submitted. Because the HTML form uses ng-submit directive so it calls SendHttpPostData function declared in the HttpPostController controller.

<div ng-app="myApp" ng-controller="HttpPostController">
    <form ng-submit="SendHttpPostData()">
        <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
        <p>Last Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
        <p>Age : <input type="number" name="age" ng-model="age" required /></p>
        <input type="submit" value="Submit" />
        <hr />
        {{ ServerResponse }}
    </form>
</div>


In below <script> code, first we have declared an AngularJS module named "myApp" that is going to be used in the HTML code. With that we have created a controller and injected $scope and $http service that will be used in the controller.

We have created a function named "SendHttpPostRequest" that is being used when the HTML form will be submitted. When user fill in the data and click on the Submit button, we are serializing form to HTTP form data format using $.param (jQuery function). By default, AngularJS uses JSON format to send the data to the server that is not by default understood by the server (ASP.NET Framework) so we will need to convert the JSON to HTTP form data format and send it. 

The serialized data is being saved into data object. Next, we are creating a config object and setting the "Content-Type" to "x-www-form-urlencoded;charset=utf-8;". Remember that by default AngularJS sends the data in JSON format so the "Content-Type" sent along with the request is JSON that is why we have changed here.

<script>
    var myApp = angular.module("myApp", []);
    myApp.controller("HttpPostController", function ($scope, $http) {

        $scope.SendHttpPostData = function () {

            var data = $.param({
                firstName: $scope.firstName,
                lastName: $scope.lastName,
                age : $scope.age
            });
        
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('/ServerRequest/PostDataResponse', data, config)
            .success(function (data, status, headers, config) {
                $scope.ServerResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ServerResponse = "Data: " + data +
"<hr />status: " + status + "<hr />headers: " + header + "<hr />config: " + config; }); }; }); </script>

Once all our required parameters for the $http.post is ready, we will fire $http.post method by passing respective parameter. 

ASP.NET Server side code

The ASP.NET server side code (in this case it is Action method of the controller of ASP.NET MVC project) simply uses Request.Form["keyname"] to retrieve data sent from the AngularJS and returning it as ContentResult. 

The response returned from server is being set to $scope.ServerResponse in the .success() method that ultimately gets bounded on the page below the form.

        public ContentResult PostDataResponse()
        {
            return Content("First name: " + Request.Form["firstName"] +
                " | Last name: " + Request.Form["lastName"] + 
                " | Age: " + Request.Form["age"]);
        }

Hope this article was useful. Do learn and share your knowledge on DotNetFunda.com, the most popular website for beginners and intermediate level professionals.

Thanks for reading.
Recommendation
Read Dynamically append data to the grid in ASP.NET with jQuery after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)