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.
/// <summary>
/// Get JSON for testimonials
/// </summary>
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 <SCRIPT> 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.