2

I want to send data to server using this function:

var _register = function (email, password, passconfirmation) {
    var data = {
        "Email": email,
        "Password": password,
        "ConfirmPassword": passconfirmation
    };

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
}

It doesn't work. My ASP.net web api doesn't receive any data. Every variable on server-side is "null". But when I do this this way:

var _register = function (email, password, passconfirmation) {
    var data = "email=" + email + "&password=" + password + "&ConfirmPassword=" + passconfirmation;

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
}

Everything works great. The problem is: the first way is much clearer than the second one, so I want to use the first one. But I have no idea what's wrong :/

Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • 1
    See this answer (http://stackoverflow.com/questions/20226169/how-to-pass-json-post-data-to-web-api-method-as-object) – LiamB Jul 21 '15 at 11:05

3 Answers3

2

I've had this issue in the past. Try

JSON.stringify(data)

Before passing it to the post. The object binder on the other side should be able to accept it then.

aminner
  • 359
  • 3
  • 10
2

remove the headers in post or change the headers like the following

 headers: { 'Content-Type': 'application/json' }

your code should be

var _register = function (email, password, passconfirmation) {
    var data = {
        "Email": email,
        "Password": password,
        "ConfirmPassword": passconfirmation
    };

    return $http.post('/api/Account/Register', data, {
        headers: { 'Content-Type': 'application/json' }
    });
}
manivannan
  • 622
  • 1
  • 4
  • 17
0

you need to do like this ..

since AngularJS, transmits data using

Content-Type: application/json

 return $http.post('/api/Account/Register', {'dataObj' : data  }, {
        headers: { 'Content-Type': 'application/json' }
    });

Your data should be a key/val pair, try: data variable will get to the server under the parameter dataObj

ngLover
  • 4,439
  • 3
  • 20
  • 42