这是我在 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/