How do I prevent JSON serialization in ASP.NET MVC?

前端 未结 5 741
我寻月下人不归
我寻月下人不归 2021-02-13 00:04

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\".<

5条回答
  •  失恋的感觉
    2021-02-13 00:56

    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.

提交回复
热议问题