views:

1792

answers:

3

I am trying to do a simple JSON return but I am having issues I have the following below.

public JsonResult GetEventData()
        {
            var data = Event.Find(x => x.ID != 0);
            return Json(data);
        }

I get a HTTP 500 with the exception as shown in the title of this question. I also tried

var data = Event.All().ToList()

That gave the same problem.

Is this a bug or my implementation?

+3  A: 

It seems that there are circular references in your object hierarchy which is not supported by the JSON serializer. Do you need all the columns? You could pick up only the properties you need in the view:

return Json(new 
{  
    PropertyINeed1 = data.PropertyINeed1,
    PropertyINeed2 = data.PropertyINeed2
});

This will make your JSON object lighter and easier to understand. If you have many properties, AutoMapper could be used to automatically map between DTO objects and View objects.

Darin Dimitrov
I think maybe selecting the ones I want may work I think the circular reference is because in Event I have IQueryable<Category> which in turn will have a IQueryable<Event>
Jon
+1  A: 

JSON, like xml and various other formats, is a tree-based serialization format. It won't love you if you have circular references in your objects, as the "tree" would be:

root B => child A => parent B => child A => parent B => ...

There are often ways of disabling navigation along a certain path; for example, with XmlSerializer you might mark the parent property as XmlIgnore. I don't know if this is possible with the json serializer in question, nor whether DatabaseColumn has suitable markers (very unlikely, as it would need to reference every serialization API)

Marc Gravell
A: 

look at this one there is a solution using ScriptIgnore attribute

stackoverflow.com/questions/1193857/subsonic-3-0-0-2-structs-tt

freddoo