User987 User987 - 1 year ago 184
jQuery Question

returning collection (list) in c# as Json

I have a method like this:

[HttpPost]
[ActionName("GetUserData")]
public ActionResult GetUserData()
{
using (var ctx = new myEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
ctx.Configuration.ProxyCreationEnabled = false;
var user = ctx.Users.Include("UserRoles").FirstOrDefault(x => x.UserId == 4);

ctx.Configuration.LazyLoadingEnabled = true;
ctx.Configuration.ProxyCreationEnabled = true;
return Json(new
{
Email = user.Email,
Roles = user.UserRoles
}, JsonRequestBehavior.AllowGet);
}
}


The post is done via jQuery like this:

$.post("/Administrator/GetUserData", function (data) {
console.log(data);
});


I'm trying to write out the returned data, but the console is showing me Internal Error 500 when I write the code like above...

In other case when returned result is like this:

return Json(new
{
Email = user.Email
// returning just email for example to see in console..
},JsonRequestBehavior.AllowGet);


Returning just email as a plain simple string works okay, but when I try to return the User's roles as an array via JSON , then I get problems like above...

The collection UserRoles is of Type ICollection...

What am I doing wrong here?

P.S. Guys I dug out the exception, it's like following:


Exception Details: System.InvalidOperationException: A circular reference was detected while serializing an object of type 'System.Collections.Generic.HashSet`1[[MyModel.Models.DatabaseConnection.UserRoles, MyEntity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'.

Answer Source

it’s clear that your model of role contains a property point to user which causes the issue.

you should select an anonymous object to return

Roles = user.Roles.Select(r=> new { name = r.Name }).ToArray();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download