ASP.NET MVC error circular reference when serializing object

1

Good afternoon dear fellows! I'm a beginner in ASP.NET MVC and C #, I'm developing a project and I've encountered a problem.

Basically, it's a store registration system. I have two tables, one called Shops and another called Owners (Where, of course, store owners are registered).

Here is an excerpt from Model Shop:

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

Here is an excerpt from Model Owner:

    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 an excerpt from 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 owner of the store. But whenever I try to save, I run into this error (OB):

A CIRCULAR REFERENCE HAS BEEN DETECTED BY SERIALIZING AN OBJECT OF THE TYPE System.Models_Loja.Lines

Can anyone help me clarify this? If you need more information, that's saying. I'm a beginner, so it must be something silly that I'm letting go of.

    
asked by anonymous 15.06.2018 / 21:35

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 comment.

    
15.06.2018 / 21:45