javascript - 如何使用 Angular js 将对象数组通过 Web api 传递到 List<>

标签 javascript c# arrays angularjs

这是我在 Controller 中的数组:

$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)?如果不是,则将 .arr 放入 JSON.stringify,如果它是对象列表,则只需发送“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)

关于javascript - 如何使用 Angular js 将对象数组通过 Web api 传递到 List<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35085426/

相关文章:

c# - 从控件获取绑定(bind)对象

javascript - 使用纯 Javascript 遍历元素

arrays - Excel VBA - 用于处理范围的数组更改单元格的格式

javascript - 如何根据 Session 值隐藏 HTML 元素

javascript - 由于 CORS 选项预检,ReactJS 无法发送 POST 请求

javascript - matDatepicker 在选择日期前 1 天发送请求

c# - 正则表达式如何匹配 2 个字段

javascript - 使用 JS 的 Microsoft Teams 图形 API - 获取组信息

c# - C# 如何将应用程序集中在父应用程序上

database - 如何在我的在线应用程序上为每个用户存储一个数组?