ASP.NET MVC error circular reference when serializing object

Asked

Viewed 616 times

1

Good afternoon dear comrades! I am a beginner in ASP.NET MVC and in C#, I am developing a project and I found a problem.

Basically, it’s a store registration system. I have two tables, one called Stores and another called Owners (Where, obviously, the owners of the stores are registered).

Here is an excerpt from the Model Store :

    [Display(Name = "Dono")]
    [ForeignKey("Dono")]
    public int IdDono { get; set; }
    public virtual Dono Dono { get; set; }

Here is an excerpt from Model Dono :

    public class Dono:BaseModel
{

    public int IdLoja { get; set; }

    [Display(Name = "Início")]
    public DateTime DtInicio { get; set; }

    public List<Loja> Loja { get; set; }
}

And here’s a snippet of my Lojacontroller:

        [HttpPost]
    [ValidateInput(false)]
    public ActionResult Adicionar(Loja loja)
    {
        string msg = "";
        if (ModelState.IsValid)
        {
            Dono dono = new Dono();
            DonoRep.Save(dono);
            lojaRep.Save(loja);

        }
        else
        {
            foreach (var item in ModelState.ToList())
            {
                foreach (var e in item.Value.Errors.ToList())
                {
                    msg += "* " + e.ErrorMessage + "<br/>";
                }
            }
        }

        return Json(new { loja = loja, msg = msg });

And my Javascript code:

function Salvar() {
var loja = {};
$('#Loja').serializeArray().map(function (x) { loja[x.name] = x.value; });
    $.ajax({
    url: $('#Loja').attr('action'),
    type: 'POST',
    data: { loja: loja },
    success: function (data) {
        if (data.loja.Id > 0) {
            CleanForm('#Loja')
            RefreshGridView(LojaGridView);
            noty({
                text: 'salvo com sucesso.',
                layout: 'bottomRight',
                type: 'success',
                timeout: 5000
            });
        }
        else {
            noty({
                text: data.msg != '' ? data.msg : 'Não foi possível salvar, certifique-se de que o formulário foi preenchido corretamente.',
                layout: 'bottomRight',
                type: 'error',
                timeout: 7000
            });
        }
    }
});

}

So what happens is this:

I created a view with a form to register the store and include the store owner. But whenever I try to save, I come across this error (OB) :

A circular reference was detected when serializing a system-like object.Models_store.Stores

Can someone help me clear this up? If you need more information, just let me know. I’m new, so it must be something silly I’m missing.

  • From what I researched, it is a mistake with my Json, but I could not solve with the solutions proposed in google.

  • Is there any Loja without Dono or Dono without Loja? 'Cause otherwise you’re in a snooker

  • In fact, it works like this: I have a table called people, another called Owners and another called Stores. The owners table is just the link between people and stores, in this case there may be owners with multiple stores, but no unattended store. When registering a store a new owner is created, containing Table Person Id and Table Store Id

  • In Dono, take the property IdLoja and alters public List<Loja> Loja { get; set; } for public virtual ICollection<Loja> Lojas { get; set; }

  • I tested this solution, but without success. Apparently, it worked with [Scriptignore]. Another mistake has now appeared, but I believe I can break my head all by myself. Thank you anyway

1 answer

0


Circular references are an indication that your design has something strange, but a faster solution than refactoring your code is to use [Jsonignore] as you yourself mentioned in the comments.

  • I searched on how to use [Jsonignore] but without success, in this search I found [Scriptignore] that apparently solved the problem..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.