In Asp.net Receiving AngularJS $http.post data using Request

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


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 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>



JQuery related Posts:


Comments

Popular posts from this blog