Jsonresult return error

Asked

Viewed 275 times

1

I’m having a hard time understanding this problem:

When I click on the line Datatable to edit the Customer data error occurs whenever the Customer has a Contact or a registered Address and this is very common.

This is code triggered when I double click on the line of Datatable:

VIEW

        // BUSCA DETALHES DO CLIENTE
        $.ajax({
            url: "ObterClientePorId",
            type: "post",
            datatype: "json",
            contentType: "application/json charset=uft-8",
            data: JSON.stringify({ "id": id }),
            success: function (data) {

                if (data != null) {
                    alert("Nome: " + data.Result.NMCLIENTE);
                    var url = "Create?id=" + id;
                    window.location.href = url;
                }

            },
            error: function (xhr, err) {
                alert(err.message);
            }
        });

Controller:

 public JsonResult ObterClientePorId(int id)
    {
        var ocliente = _IRepositorio.ListarClientePorId(id);
        return Json(new { Result = ocliente }, JsonRequestBehavior.AllowGet);
    }

Repository:

public TBCliente ListarClientePorId(int? id)
    {
        return _repositorio.Clientes.FirstOrDefault(c => c.TBCLIENTEID == id);

    }

PRINT OF THE EXECUTION:

View:

inserir a descrição da imagem aqui

Controller:

inserir a descrição da imagem aqui

Repository: inserir a descrição da imagem aqui

Controller

Note that the Customer has a registered Address

inserir a descrição da imagem aqui

View:

Here the error occurs, always when the Customer has an Address or a Contact that is common:

inserir a descrição da imagem aqui

Thank you!

**Error when double clicking **

inserir a descrição da imagem aqui

  • Your ajax is returning an error. If it was returning Success it would show its string "Name: something". As he is falling into error, he is showing Undefined. Swap your ajax error with the following function -> error: Function (result) { Alert(result.responseText)}, and see which error is coming from your server.

  • 1

    Nikofoxxx changed Alert as you suggested and the error returned is circular reference: '{System.Data.Entity.Core.Objects.Internal.Entitywrapperwithoutrelationships<System.Data.Entity.DynamicProxies.Tbcliente_b9c53e0400b8bdc8bc0a93f5d237906b8cc8c546fffac9d110ee207edc782c>}', I will add the Alert print on the question body to get better understanding.

1 answer

3


You have a circular reference problem. The JSON serializer attempts to serialize an entity A, which references an entity B, and which in some way refers back to A.

There’s already an answer to that here.

Additionally, it is best not to use the repository approach when using Entity Framework. It brings no advantage and still causes problems.

Browser other questions tagged

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