返回JsonResult从MVC控制器对象的列表 [英] Return JsonResult with List of objects from MVC controller

查看:161
本文介绍了返回JsonResult从MVC控制器对象的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple method in my MVC controller:

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

这是一个区域对象:

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; }
}



这是我如何调用视图中的方法:

And this is how I call the method from the view:

$.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;
    }
});



我已经检查方法在控制器和区对象的列表被创建。你有什么想法,为什么我得到500内部服务器错误时,该方法是从视图叫什么?当我回到别的(如Dictionary对象)一切正常,只是当我的目标是区域列表为JSON我得到一个错误转换。

I have checked the method in the controller and a list of Area objects gets created. Would you have any idea why do I get the 500 internal server error when the method is called from the view? When I return anything else (like a Dictionary object) everything works fine, it's just when I aim to convert the List of Areas into Json I get an error.

推荐答案

由于类包含公司公司包含区集则可能是未通过JSON序列化支持的对象层次循环引用。为了解决这个问题,返回的匿名对象,只有那些你需要的,例如:

Since class Area contains Company and Company contains collection of Area you likely have circular references in your object hierarchy which is not supported by the JSON serializer. To solve this, return anonymous objects with only those properties you need, for example

[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);
}

这篇关于返回JsonResult从MVC控制器对象的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆