While developing an ASP.NET MVC app, I\'m finding a few places where my JsonResult actions throw an exception \"A circular reference was detected while serializing an object\".<
I've generally found that for complex objects its best to just serialize by creating a temporary 'inbetween' object :
For instance for testimonials I do the following. I actually do this in the codebehind for my ASPX model page.
This creates a nice JSON object. You'll notice I can even refactor my model and the page will still work. Its just another layer of abstraction between the data model and the page. I dont think my controller should know about JSON as much as possible, but the ASPX 'codebehind' certainly can.
///
/// Get JSON for testimonials
///
public string TestimonialsJSON
{
get
{
return Model.Testimonials.Select(
x => new
{
testimonial = x.TestimonialText,
name = x.name
}
).ToJSON();
}
}
In my ASPX I just do this in a block:
var testimonials = <%= TestimonialsJSON %>;
// oh and ToJSON() is an extension method
public static class ObjectExtensions
{
public static string ToJSON(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
I'm ready for the backlash against this suggestion... bring it on...
I'm not accessing data, merely reformatting a model for the View. This is 'view model' logic, not 'controller model' logic.