C# – A circular reference was detected while serializing an object of type

asp.net-mvccjson

I tried this code in my controller :

List<ProductListingModels> prom = new List<ProductListingModels>();

prom.Add(new ProductListingModels()
{
    ID = item.ID,
    Name = item.Name,
    DepartmentID = item.DepartmentID.Value,
    BrandID = item.BrandID.Value
});

jr.Data = prom;
jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return Json(new
{
    ja = jr.Data,
}, JsonRequestBehavior.AllowGet);

This is my ProductListingModel :

 public class ProductListingModels:ItemEntityDataContext
 {
   public int ID { get; set; }
   public string Name { get; set; }
   public int DepartmentID { get; set; }
   public int BrandID { get; set; }
 }

It was an error :

A circular reference was detected while serializing an object of type.

But if I change from adding the object "prom" to adding something like string or integer, It works well. I don't know what problem happen of how to adding my objects.

Can any one show me the solution. Welcome to all your question and answer, Thanks so much.

Best Answer

I suspect the problem is with references ItemEntityDataContext superclass might hold to other objects. It is always a good idea to copy your data to a viewmodel class for passing into views. In your case however just use LINQ to select fields into new anonymous type and serialize with json. Something like this:

jr.Data = prom.Select(p => new 
{ 
    ID = p.ID, 
    Name = p.Name, 
    DepartmentID = p.DepartmentID,
    BrandID = p.BrandID
}).ToArray();