[英]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 : 这是我的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. 但是,如果我从添加对象“ prom”更改为添加诸如字符串或整数之类的东西,则效果很好。 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.
欢迎来到您所有的问题和答案,非常感谢。
I suspect the problem is with references ItemEntityDataContext superclass might hold to other objects. 我怀疑问题在于引用ItemEntityDataContext超类可能持有其他对象。 It is always a good idea to copy your data to a viewmodel class for passing into views.
将数据复制到viewmodel类以传递到视图中总是一个好主意。 In your case however just use LINQ to select fields into new anonymous type and serialize with json.
但是在您的情况下,只需使用LINQ将字段选择为新的匿名类型并使用json进行序列化即可。 Something like this:
像这样:
jr.Data = prom.Select(p => new
{
ID = p.ID,
Name = p.Name,
DepartmentID = p.DepartmentID,
BrandID = p.BrandID
}).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.