An issue arose with a circular reference during the serialization of a JSON MVC object

I am trying to follow the instructions provided in this video on Youtube.

Here is the code in my controller:

public ActionResult loaddatacate()
        {
            BBDbModel context = new BBDbModel();
            context.Configuration.ProxyCreationEnabled = false;
            var data = context.Drinks_Category.ToList();
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }

This is how it looks in my view:

<script type="text/javascript">
        $(document).ready(function (e) {
            $("#example1").DataTable({
                "ajax": {
                    "url": "/Admin/AdminHome/loaddatacate",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Id_category", "autowidth": true },
                    { "data": "Name_category", "autowidth": true },
                    { "data": "Parent", "autowidth": true }
                ]
            });
            var Parent =  @Html.Raw(Json.Encode(ViewBag.Parent));
            $(".parent").autocomplete({
                source: Parent
            });
        });

The database table "Drinks_category" has 3 columns: Id_category, Name_category, and Parent.

However, I encountered an error:

A circular reference was detected while serializing an object of type 'WebApplication3.Models.Framework.Drinks_Category'.

The Drinks_Category class is defined as follows:

public partial class Drinks_Category
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Drinks_Category()
        {
            Drinks = new HashSet<Drink>();
            Drinks_Category1 = new HashSet<Drinks_Category>();
        }

        [Key]
        [StringLength(10)]
        public string Id_category { get; set; }

        [StringLength(20)]
        public string Name_category { get; set; }

        [Required]
        [StringLength(10)]
        public string Parent { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Drink> Drinks { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Drinks_Category> Drinks_Category1 { get; set; }

        public virtual Drinks_Category Drinks_Category2 { get; set; }
    }

I would appreciate any help with resolving this issue. Thank you!

Answer №1

One common occurrence of this type of error is when attempting to serialize a class, such as 'class1', that contains a reference to another class, such as 'class2', which in turn references back to 'class1'. This creates a circular reference loop where 'class1' points to 'class2' and 'class2' points back to 'class1'.

Answer №2

To prevent the serializer from encountering loop references, use the following code:

var serializedData = JsonConvert.SerializeObject(myList, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});

Then, send the result back in this format:

return Json(new { serializedData = data }, JsonRequestBehavior.AllowGet);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in parsing JSON with Google Gson

Can anyone help me with putting a Map into listMap using Gson and displaying it in listView? I am having trouble understanding how to do it. Below is my code snippet for the button onClick event: map = new HashMap<>(); map.put("title", edttext1.get ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

Reactjs: Tips for precisely cropping an image to a specific aspect ratio using client-side techniques

Looking to crop an image with a minimalist approach to achieve a specific aspect ratio. For instance, if we have an image sized at 3038 x 2014 px, and desire a 1:2 aspect ratio, we would crop it to 3021 x 2014 px. The crop would be made from the center of ...

Adjusting the size of images in real time

Currently, I am in the process of creating a Fluid grid style website and I am looking to decrease the size of all images by 75% when the screen is below 1280px, 50% at 800px, and so forth. Is there a way to achieve this using the IMG tag? My attempt so ...

Tips for building a carousel-style transition using React Router

I am looking to implement a carousel animation in my React Router. My website has pages named A, B, C, and D. When transitioning from page A to B, I want the animation to move from right to left. When going from B to A, I want it to move from left to rig ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

The process of linking a JsonObject attribute to XML using MOXy

I am currently working with the following class structure: @XmlRootElement(name = "Root") class MyClass { @XmlElement(name = "Entries") JsonObject getProperty() { ... } } My goal is to generate the following XML output upon marshalling: <Roo ...

The issue with the min attribute for number inputs not functioning properly when using decimal

When inputting the value 3 in the field and clicking on submit in the HTML snippet below, Chrome displays an error message stating: Please enter a valid value. The two nearest valid values are 2.0001 and 3.0001. This is confusing because I have set the mi ...

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

The stubborn Node and Passport are refusing to update the password using user.setPassword

Currently, I am working on setting up my program to update a user's password only when the old one is confirmed as correct. Most of the code functions as expected except for one specific line: router.put("/:id/edit_password", isLoggedIn, isAdministra ...

The query is found to have multiple values when utilized as an expression

I am working with a table called tblTimeSlotInformation which contains the fields: Username, EmpName, Date (date), Day, StartingTime (time(7)), EndingTime (time(7)), TimeSlot, Topic, and ClassroomNo. The issue I am facing is that data cannot be inserted i ...

Unable to center align a .swf file vertically

I recently added a .swf file to my webpage within a div element, and I attempted to center it vertically in the middle of the div. Unfortunately, my attempts were only successful in horizontal alignment, which is not the desired outcome. I even tried pla ...

Generate dynamic concentric rings with either CSS, Canvas, or SVG for a fluid and scalable design

Looking to create a graph similar to these examples: http://bl.ocks.org/cmdoptesc/6228457 or like this Wanting the graph to be able to scale based on browser width without using javascript if possible. Ideally, looking for a CSS-only solution, but open ...

Utilizing TypeScript to Define Object Properties with String Keys and Values within Parentheses

I am in the process of developing a telegram bot I have the need to save all my messages as constants My message schema is structured as follows: type MessagesSchema = { [K in keyof typeof MessagesEnum]: string } Here is an example implementatio ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

The function Getter is expected, but an error has occurred with "getters.doubleCounter" returning a value of 20 in VUEX

Currently, I am diving into the world of Vuex and encountering some challenges along the way. In my attempt to create a getter on my vuex instance, I am facing an error when trying to display data from one of my components: The getter should be a functi ...

Make sure to load the gif image before any other images are loaded from the css

Hey there, I'm attempting to display a GIF image before the actual image loads. I found a great example to accomplish this: Example: Java Script function loadimage(imgsrc, change){ var loadimage = new Image(); loadimage.onload = changesrc(imgsrc, c ...