【问题标题】:How to pass array of object through web api to a List<> using angular js如何使用角度js通过web api将对象数组传递给List<>
【发布时间】:2016-05-07 05:48:00
【问题描述】:

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

$scope.arr = [];

    $scope.arr.push({

        QuestionId1: firstQuestionId,
        QuestionId2: secondQuestionId,
         SecurityAnswer1: firstQuestionAnswer,
         SecurityAnswer2: secondQuestionAnswer
        });

AccountService.SubmitSecurityAnswer($scope);

那么这是我在角度服务中的 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..我认为“数据:d.arr”的格式不正确,是吗? 请帮忙。

【问题讨论】:

  • 尝试将内容类型更改为 application/JSON,并删除 transformFormRequest。

标签: javascript c# arrays angularjs


【解决方案1】:

在您的客户端代码中进行以下更改以将请求作为 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)

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 2018-05-12
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多