Bartosz
Bartosz

Reputation: 4592

Return JsonResult with List of objects from MVC controller

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

This is an area object:

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

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.

Upvotes: 19

Views: 92294

Answers (2)

user4584103
user4584103

Reputation:

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

Upvotes: 5

user3559349
user3559349

Reputation:

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

Upvotes: 25

Related Questions