通过角度js中的http post传递对象集合

时间:2015-11-24 12:43:41

标签: javascript angularjs asp.net-mvc

我通过角度js中的http post传递了一组对象。

代码如下:

  $scope.selectedContent = function () {       
        var contents = $filter('filter')($scope.data.ContentId, { Selected: true });  // I could able to get all the selected objects here, No problem with it        
        var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
        var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
        promise.success(function () {            
            window.location.reload();
        });



        [ReferrerFilterAttribute]
        [HttpPost]
        [System.Web.Http.ActionName("CmsPublishApprovedContent")]
        public void CmsPublishApprovedContent(string jsonData)
        {
            var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);

            foreach (var content in contents)
            {
                _contentService.PublishContent(content.ContentId,  userId);
            }       
        }
    }

如果有5条或更少的记录,上面的代码可以正常工作。如果有更多记录,我可以获得所有选定的记录 变量&#39;内容中的对象&#39;。但是在为所有这些对象转换为Json时会出现问题。一世 有大约500条记录可以通过。怎么办?

没有特别的理由转换为JSON数据。我只需要提取所有选定项目的ID。我修改了上面的代码如下:

$scope.selectedContent = function () {        
        var contents = $filter('filter')($scope.data, { Selected: true });
        var abc = [];
        angular.forEach(contents, function(content)
        {
            abc.push(content.ContentId); // got all the ids in the array now
        });

        var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
        promise.success(function () {
            window.location.reload();
        });
    }

我刚拿了一个数组并将所有内容ID推入其中。我现在能够看到阵列中的所有ID。我试图像上面那样传递数组。 如何在后面的代码中检索那些数组。

[ReferrerFilterAttribute]
        [HttpPost]
        [System.Web.Http.ActionName("CmsPublishApprovedContent")]
        public void CmsPublishApprovedContent(int[] abc)
        {}

我没有看到在int [] abc下获得的任何值。上面方法调用中参数的数据类型是什么。

3 个答案:

答案 0 :(得分:1)

您需要$http.post方法的第二个参数。您必须通过POST请求发送此类数据,而不是查询url。您可以将一些数据放入帖子请求的正文中。

你需要这个:

var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});

此外,您必须准备好在后端处理此请求。

答案 1 :(得分:0)

是否有任何特定原因要将此数据作为JSON传递?。

如果您在这种情况下使用Web API,您可以按原样传递对象,但只能确保Web API方法中的集合包含javascript集合中的所有属性

答案 2 :(得分:0)

感谢您的所有帖子。没有转换为Json,它工作正常。代码如下。

$scope.selectedContent = function () {        
        var contents = $filter('filter')($scope.data, { Selected: true });
        var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
        promise.success(function () {
            window.location.reload();
        });
    }

并且签名将是

public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
        {
}