如何从Controller返回Json List对象

时间:2017-02-10 23:31:53

标签: jquery asp.net ajax asp.net-mvc-5

在我的jquery中,我调用$.ajax()函数,我没有任何问题。我的问题在于成功部分,我希望能够做到以下几点:

$.ajax('/Home/GetData/' + id, // request url
{
    contentType: "application/json; charset=utf-8",
    async: true,
    dataType: 'json',
    type: "POST",
    succes: function (response) { // success callback function
        alert("OK");
    },
    error: function(data) {
        alert("Dynamic content load failed.");
    }
});

和我的控制员:

[HttpPost]
public JsonResult GetData(int Id)
{
    var results = (from subCategory in _db.SubCategories
     where subCategory.CategoryId == Id
     select subCategory).ToList();

    return Json(new { Response = results } , JsonRequestBehavior.AllowGet);
}

我总是收到错误消息。如何从控制器获取对象列表并在View中处理一个。

2 个答案:

答案 0 :(得分:1)

I solved my problem with this..

public ActionResult GetData(int Id)
    {
        var results = (from subCategory in _db.SubCategories
            where subCategory.CategoryId == Id
            select subCategory).ToList();

        var list = JsonConvert.SerializeObject(results,
            Formatting.None,
            new JsonSerializerSettings()
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            });

        return Content(list, "application/json");
    }

答案 1 :(得分:0)

你的GetData()方法是POST,你正在返回JsonRequestBehavior.AllowGet它不应该在那里写。你必须改变这个

 return Json(new { Response = results } , JsonRequestBehavior.AllowGet);

试试这个:

[HttpPost]
public JsonResult GetData(int Id)
{
    var results = (from subCategory in _db.SubCategories
     where subCategory.CategoryId == Id
     select subCategory).ToList();

return Json(results);
}