如何使用角度 js 通过 Web api 将对象数组传递到列表<>

How to pass array of object through web api to a List<> using angular js

本文关键字:列表 数组 对象 何使用 js 通过 api Web      更新时间:2023-09-26

这是我在控制器中的数组:

$scope.arr = [];
    $scope.arr.push({
        QuestionId1: firstQuestionId,
        QuestionId2: secondQuestionId,
         SecurityAnswer1: firstQuestionAnswer,
         SecurityAnswer2: secondQuestionAnswer
        });

AccountService.SubmitSecurityAnswer($scope);

那么这是我在 Angular 服务中的 API:

fact.SubmitSecurityAnswer = function (d) {
    debugger;
    return $http({
        method: 'POST',
        url: API_RESOURCES.API_Domain + 'api/Account/SaveSecurityAnswers',
        headers: { 'content-Type': 'application/x-www-form-urlencoded' },
        transformRequest: function (obj) {
            var str = [];
            for (var p in obj)
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
        isArray: true,
        data: d.arr
        }).success(function (response) {
        return response;

此 api 调用的 C# 函数是:

 public HttpResponseMessage SaveSecurityAnswers(List<SecurityQuestion_CustomerMap> obj)
    {

当我通过断点检查"obj"时,它显示 count=0..我认为"data: d.arr"的格式不正确还是不正确?请帮忙。

在客户端代码中进行以下更改以将请求作为 json 传递。我假设对象列表被添加到您要传入的另一个对象 (d) 中?如果没有,那么在 JSON.stringify 中删除 .arr,如果它是对象列表,只需发送"d"。

fact.SubmitSecurityAnswer = function (d) {
    return $http({
        url: API_RESOURCES.API_Domain + 'api/Account/SaveSecurityAnswers',
        dataType: 'json',
        method: 'POST',
        data: JSON.stringify(d.arr),
        headers: {
           "Content-Type": "application/json"
        }
    });
}

并更改终结点以在请求正文中查找对象列表。

[HttpPost]
public HttpResponseMessage SaveSecurityAnswers([FromBody]List<SecurityQuestion_CustomerMap> obj)