将json数据发布到angularjs中的WebAPI方法

时间:2014-06-03 03:58:08

标签: c# json angularjs asp.net-web-api

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

如何使用angularjs' s $ http发布上述json数据到以下WebAPI方法?

[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);
    }

我试过了:

$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) {                
     });

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:5)

刚试过这个,工作正常:

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

}

$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);

您收到了什么错误回复?可能是因为您的请求中没有包含授权标头,并且由于您的Api端点上的Authorize属性而获得401?