Return JsonResult with List of objects from MVC controller

后端 未结 2 791
庸人自扰
庸人自扰 2020-12-06 00:37

I have a simple method in my MVC controller:

[HttpPost]
public JsonResult GetAreasForCompany(int companyId)
{
   var areas = context.Areas.Where(x => x.Co         


        
相关标签:
2条回答
  • 2020-12-06 01:23

    Return List Object as Json (Also useful for JqueryUI and Linq Method)

    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);
    }
    
    0 讨论(0)
  • 2020-12-06 01:27

    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);
    }
    
    0 讨论(0)
提交回复
热议问题