为什么我不在控制器中捕获此JSON?

时间:2016-03-11 22:03:55

标签: json ajax asp.net-mvc post

所以我传递了一个像

这样的对象数组
{ QuestionId: 24,
  AnswerVal: -1,
  PartnerId: "e0e8035d-046a-45c5-b7e5-7986865ce37c",
  VersionId: 1 }

我的控制器是

[HttpPost]
public async Task<ActionResult> SubmitAnswers ( List<AnswerSubmission> A )

其中AnswerSubmission

定义
public class AnswerSubmission
{
    public Guid PartnerId { get; set; }
    public int AnswerVal { get; set; }
    public int QuestionId { get; set; }
    public int VersionId { get; set; }
}

它没有工作,因为我从

得到空的回应
$.ajax({
    method: 'POST',
    url: '/Answers/SubmitAnswers',
    dataType: 'json',
    data: JSON.stringify(Answers),
    complete: function ( retobj ) {
        console.log(retobj);
    }
});

如果我制作我的控制器

[HttpPost]
public async Task<ActionResult> SubmitAnswers ( List<AnswerSubmission> A )
{
    return Json(A);
}

作为测试。

1 个答案:

答案 0 :(得分:1)

  

{   QuestionId:24,
  AnswerVal:-1,
  PartnerId:&#34; e0e8035d-046a-45c5-b7e5-7986865ce37c&#34;,
  VersionId:1   }

不是&#34;对象数组&#34; ,它是一个对象。

另外另外contentType: "application/json; charset=utf-8"由@Stephen Muecke评论

Jquery的:

$.ajax({
    method: 'POST',
    url: '/Answers/SubmitAnswers',
    dataType: 'json',
    //add this
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(Answers),
    complete: function (retobj) {
        console.log(retobj);
    }
}).done(function (d) {
        console.log(d); //probably what you're really looking for..
});

控制器:

[HttpPost]
public ActionResult SubmitAnswers(AnswerSubmission A)//an object, not an array of objects
{
    return Json(A);
}