Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting json data to WebAPI method in angularjs

$scope.items = {2: true, 4: true, 5: true, 7: true, 9: true, 10: true, 11: true };

How do I post the above json data to the following WebAPI method using angularjs's $http?

[Authorize]
[HttpPost]
[Route("moveemployees")]
public HttpResponseMessage MoveEmployees(Dictionary<decimal, bool> employeeList)     
    {
         // employeeList doesn't contain any items after the post
         return Request.CreateResponse(HttpStatusCode.OK);
    }

I tried :

$http({
        method: 'POST',
        cache: false,
        url: $scope.appPath + 'Employee/moveemployees',
        data: { employeeList : $scope.items },
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
           }
        }).success(function (data, status) {
            $scope.infos.push('Employees Moved Successfully');
            $scope.errors = [];
        }).error(function (data, status) {                
     });

What's wrong with my code?

like image 351
kvothe Avatar asked Jun 03 '14 03:06

kvothe


People also ask

How do I post JSON to a REST API endpoint?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

What is$ http in AngularJS?

$http is an AngularJS service for reading data from remote servers.


1 Answers

Just tested this, works fine:

[Route("moveemployees")]
public void Post(Dictionary<decimal, bool> employeeList)
{

}

and:

$scope.items = { 2: true, 4: true, 5: true, 7: true, 9: true, 10: true, 11: true };
var config = {
    method: "POST",
    url: "moveemployees",
    data: $scope.items
};
$http(config);

What error response are you getting? Might be something like not including an authorization header in your request and getting a 401 due to the Authorize attribute on you Api endpoint?

like image 77
Mohammad Sepahvand Avatar answered Oct 13 '22 09:10

Mohammad Sepahvand