MVC5控制器没有收到JSON对象

时间:2017-04-22 06:45:00

标签: javascript json ajax asp.net-mvc knockout.js

我有一个控制器,方法如下:

public JsonResult Save(List<BlogInfo> list)
{
    return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}

我在客户端发了一条ajax帖子如下:

$.ajax({
    url: "Home/Save",
    type: "post",
    contentType: "application/json",
    data: ko.mapping.toJSON(ViewModel),
    success: function (response) {
        alert(response.Status);
    }
});

我的问题是控制器的list参数始终为null。我尝试将其更改为字符串而不是列表,但也是null。

使用Fiddler,我可以看到JSON正在传递如下:

{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}

1 个答案:

答案 0 :(得分:0)

您显示的JSON不代表数组,因此您不可能期望将其绑定到服务器上的列表。要实现这一点,请确保从客户端发送一组对象:

data: ko.mapping.toJSON(ViewModel.Data);

这里我们采用表示数组的ViewModel.Data属性,以便我们只发送所需的JSON:

[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":‌​"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description‌​","Tags":[]}]