JSON serialization with a circular reference detected

asp.net-mvc-5 c# entity-framework-6 jquery json

Question

I created two classes "Candidat" and "Experience". The Candidate may have many experiences

public class Consultant
{
    public int ConsultantID { get; set; }
    public string ConsultantNom { get; set; }
    public string ConsultantPrenom { get; set; }
    public string ConsultantTitre { get; set; }
    public Disponibilite ConsultantDisponibilite { get; set; }
    public virtual ICollection<Experience> Experiences { get; set; }

}

public class Experience
{
    public int ExperienceID { get; set; }
    public virtual Consultant Consultant { get; set; }
    public int ConsultantID { get; set; }
    public string ExperienceNomSociete { get; set; }
    public string ExperiencePoste { get; set; }
    public DateTime ExperienceDebut { get; set; }
    public DateTime ExperienceFin { get; set; }
    public string ExperienceCompetences { get; set; }

In my Controller when I search for all candidates I writed this code

public JsonResult ConsultantsList()
    {

        var consultants = from c in _consultantRepository.getConsultants()
                          select c;

        return Json(consultants, JsonRequestBehavior.AllowGet);
    }

The problem is when I put a break point I recieve the results, but in my page there is a problem "A circular reference was detected while serializing an object of type".

This is how I parse data with JQuery:

 function PopulateConsultantList() {
        $.ajax({
            type: "GET",
            url: "/Consultants/ConsultantsList",
            success: function (data) {
                console.log(data);
                var json = $.parseJSON(JSON.stringify(data));
                console.log(json);
                var corpsTR = '';
                $.each(json, function (i, item) {
                    corpsTR += '<tr><td>' + item.ConsultantPrenom + " " + item.ConsultantNom + '</td>'
                        + '<td>' + item.ConsultantTitre + '</td>'
                        + '<td>Immédiate</td>'
                        + '<td><a href="/Consultants/Details/' + item.ConsultantID + '" class="btn btn-default btn-icon"><i class="fa fa-file-text-o"></i></a>&nbsp;<a href="/Consultants/Delete/' + item.ConsultantID + '"  class="btn btn-danger btn-icon"><i class="fa fa-trash-o"></i></a></td></tr>';
                });
                $("tbody").append(corpsTR);
            }
        });
    }

PS: When Experiences are empty, no problem issued. Thank you

1
-1
2/18/2017 12:05:26 PM

Accepted Answer

Remove the Consultant property from Experience, or add a JsonIgnore attribute to it.

1
2/18/2017 12:23:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow