Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A circular reference was detected while serializing an object of type

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.

like image 232
Nothing Avatar asked Apr 24 '12 10:04

Nothing


1 Answers

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();
like image 177
LeffeBrune Avatar answered Oct 13 '22 16:10

LeffeBrune