Well, let's do it in parts.
Why is this happening?
Because you have virtual properties. If you use EF, you really need them if you use Lazy download. You can configure your EF to not do this in this example:
context.Configuration.ProxyCreationEnabled = false;
where context is ObjectContext or DbContext ... this assumes you are using EF. But for most scenarios, this is not very good.
Possible Solution
As I always say: "There are no good or bad solutions, just different ways, and it depends on the context," saying that you can create dynamic objects.
If you only need to serialize a unique object, you can do something like this
Json(new {@property1=yourObject.property1, @property2=yourObject.property2})
If you have a list, you can do this:
var list = new List<dynamic>(); foreach(var item in myRepository.GetAll()) { list.Add(new { @property1= item.property1, @property2= item.property2, @property3= item.property3 }); } return Json(list, JsonRequestBehavior.DenyGet);
I tried to make this as general as possible. Hope this helps someone!
Best wishes and a very nice day! :)
source share