简体   繁体   中英

AngularJS Post data as key-value pair to a asp.net page

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

Example Data

 {fullName: "Vikas Bansal", userId: "1001387693259813", userimageurl: "http://graph.facebook.com/1001387693259813/picture?width=250&height=250"}

Angular Code

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

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

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

Asp.net 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 asp.net page all variables are null.

在此处输入图片说明

EDIT

By changing content type to 'Content-Type': 'application/json; charset=utf-8' '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"];

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", $scope.name);
postData.append("userId", $scope.userId);
postData.append("userimageurl", $scope.userImage);

$http.post(postUrl, postData, {
    transformRequest: angular.identity,
    headers: { 'Content-Type': undefined }
}).then(function(data) {
    //success
}, function(error) {
    //error
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM