返回JsonResult与MVC控制器中的对象列表

Bar*_*osz 17 c# ajax asp.net-mvc jquery json

我的MVC控制器中有一个简单的方法:

[HttpPost]
public JsonResult GetAreasForCompany(int companyId)
{
   var areas = context.Areas.Where(x => x.Company.CompanyId == companyId).ToList();
   return Json(areas);
}
Run Code Online (Sandbox Code Playgroud)

这是一个区域对象:

public class Area
{
    public int AreaId { get; set; }

    [Required]
    public string Title { get; set; }
    public bool Archive { get; set; }

    public virtual Company Company { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这就是我从视图中调用方法的方式:

$.ajax({
    url: '@Url.Action("GetAreasForCompany")',
    type: 'POST',
    async: false,
    data: "{'companyId': " + companyId + "}",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: function () {
        alert("Server access failure!");
    },
    success: function (result) {
        response = result;
    }
});
Run Code Online (Sandbox Code Playgroud)

我检查了控制器中的方法,并创建了Area对象列表.您是否知道为什么在从视图调用方法时出现500内部服务器错误?当我返回任何其他东西(比如一个Dictionary对象)时,一切正常,只是当我的目标是将区域列表转换为Json时,我得到一个错误.

小智 21

由于类Area包含CompanyCompany包含Area您可能在对象层次结构中具有循环引用的集合,而JSON序列化程序不支持该循环引用.要解决此问题,请返回仅包含所需属性的匿名对象

[HttpPost]
public JsonResult GetAreasForCompany(int companyId)
{
  var areas = context.Areas
    .Where(x => x.Company.CompanyId == companyId)
    .Select(a => new
    {
      AreaId = a.AreaId,
      Title = a.Title
    });
  return Json(areas);
}
Run Code Online (Sandbox Code Playgroud)

  • @AaronCampbell,没有理由你需要使用`[HttpPost]`,因为它不会改变任何数据 - 也可能是`[HttpGet]`(除非你不想将url添加到浏览器历史记录中).刚用过什么OP :) (3认同)

小智 5

以 Json 形式返回列表对象(对于 JqueryUI 和 Linq 方法也很有用)

public ActionResult GetItemList()
{
    var search = Request.Params["term"];

    var itemList = (from items in db.TblItems where items.ItemName.StartsWith(search) select new { label = items.ItemName, value = items.ItemName }).ToList();

    return Json(itemList, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)