Vikas Bansal Vikas Bansal - 2 years ago 140
Javascript Question

AngularJS Post data as key-value pair to a page

I am trying to post key-value pair data from angular application to a page however I am not able to receive the result at the page.

Example Data

{fullName: "Vikas Bansal", userId: "1001387693259813", userimageurl: ""}

Angular Code

var postData = {
fullName: $,
userId: $scope.userId,
userimageurl: $scope.userImage

var postUrl = 'http://localhost:41115/Index.aspx';

url: postUrl,
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
data: postData
}).then(function (responce) {
}, function (responce) {
}); Page Code

protected void Page_Load(object sender, EventArgs e)
var userId = Request.Form["userId"]; /// getting null
var fullName = Request.Form["fullName"]; /// getting null
var img = Request.Form["userimageurl"]; /// getting null

In page all variables are null.

enter image description here


By changing content type to
'Content-Type': 'application/json; charset=utf-8'
in angularJs post request

and by using
var strJSON = (new StreamReader(Request.InputStream).ReadToEnd());
I am able get the posted json

but I am still wondering if there is a way to get key-value pairs directly?

like this
var userId = Request.Form["userId"];

Answer Source

It's because your payload is actually JSON but you tried to pass as a FormData object.

You'll need to make a FormData() object. Then

(1) Tell AngularJs not to serialize it by using the angular.identity function.

(2) Angular's default header for PUT and POST requests is application/json, so you'll want to override that too. The browser sets the Content-Type to multipart/form-data and fills in the correct boundary.

Try this:

var postData = new FormData();
postData.append("fullName", $;
postData.append("userId", $scope.userId);
postData.append("userimageurl", $scope.userImage);

$, postData, {
    transformRequest: angular.identity,
    headers: { 'Content-Type': undefined }
}).then(function(data) {
}, function(error) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download