0

my problem is the response from controller, goes directly to ajax error function.

My respository

tbMenu has a unary relationship.

    public object GetList()
    {
        try
        {
            MvcSecurityEntities contexto = new MvcSecurityEntities();
            contexto.ContextOptions.ProxyCreationEnabled = false;
            contexto.ContextOptions.LazyLoadingEnabled = false;
            return contexto.CreateObjectSet<tbMenu>().ToList();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Business

public class MenuBusiness : IDisposable
{
    private MenuRepository _menuRepository = null;
    public MenuBusiness()
    {
        _menuRepository = new MenuRepository();
    }

    public object GetList()
    {
        return _menuRepository.GetList();
    }

    public void Dispose()
    {
        this.Dispose();        
    }
}

Controller

    [HttpGet]
    public JsonResult GetList()
    {
        List<tbMenu> lista = new List<tbMenu>();

        MenuBusiness menuBusiness = new MenuBusiness();
        lista = (List<tbMenu>)menuBusiness.GetList();          

        var sarasa = new JsonResult { Data = lista, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        return sarasa;
    }

Ajax

$(document).ready(function () {
LoadContacts();});


function LoadContacts() {
$('#update_panel').html('Loading Data...');
debugger;
$.ajax({
    url: '/Menu/GetList',
    contentType: 'application/json; charset=utf-8',
    type: 'GET',
    dataType: 'json',
    success: function (d) {
        if (d.length > 0) {
           alert('Ok');//here I build the table, but in this sample, i think does not matter.
        }
    },
    error: function () {
        alert('Error! Please try again.');
    }
});

When I load the POCO entities with a for, that works fine. For example

    public List<tbMenu> ObtenerLista()
    {
        tbMenu menu = null;
        List<tbMenu> lista = new List<tbMenu>();
        for (int i = 0; i < 10; i++)
            lista.Add(menu = new tbMenu() { men_id = i, men_id_padre = i + 10, men_nombre = "nombre " + i.ToString(), men_url = "url " + i.ToString(), men_observaciones = "obs " + i.ToString() });

        return lista;
    }

I think the error is the linq object... I searched in internet and I found just the set

contexto.ContextOptions.ProxyCreationEnabled = false;

In my context, but this does not work.

Any suggestions? Help me pls!

Lrodriguez84
  • 714
  • 7
  • 8
  • What error do you get? What do you see in the Network tab in the dev tools? – SLaks Aug 31 '15 at 15:33
  • Your `Dispose()` method is completely wrong. – SLaks Aug 31 '15 at 15:33
  • 1
    Never write `throw ex`. http://stackoverflow.com/a/2999314/34397 – SLaks Aug 31 '15 at 15:34
  • A circular reference was detected while serializing an object of type 'MvcSecurity.Entities.tbMenu'. – Lrodriguez84 Aug 31 '15 at 15:52
  • SLaks, thank you very much for the corrections! I will investigate how to implement. The error is above. thanks again! – Lrodriguez84 Aug 31 '15 at 15:55
  • To follow-up on SLaks comment regarding `Dispose()`, this [SO answer](http://stackoverflow.com/a/538238/168840) does a good job of explaining the _how_ and _why_. – John B Aug 31 '15 at 16:02
  • If you getting a circular reference exception its because you model contains a property which references itself so you need to return only the properties you need (as you are currently doing, although you can just return a collection of anonymous objects using `var data = lista.Select(l => new { someValue = l.someProperty, anotherValue = l.anotherProperty, ...}); return Json(data, JsonRequestBehavior.AllowGet);` –  Sep 01 '15 at 01:06

1 Answers1

1
var sarasa = new JsonResult { Data = lista.Select(item=> new 
{
    Field1 = item.Field1,
    Field2 = item.Field2,
    ...
    Fieldn = item.Fieldn

}), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        return sarasa;

Where Field1, Field2, Fieldn properties need to be replaced with actual properties from tbMenu object.

Another possibility would be to add

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

in Global.asax in Application_Start method. For this you need to reference Newtonsoft.Json.

cristis
  • 56
  • 4
  • Hi cristis! thanks to reply. I added the code to field to field, but when i added the unary relationship, show the "circular reference was detected while..." error { men_id = item.men_id, men_id_padre = item.men_id_padre, men_nombre = item.men_nombre, men_observaciones = item.men_observaciones, men_url = item.men_url, tbMenu1 = item.tbMenu1 } If I comment "tbMenu1 = item.tbMenu1" works fine. But I need the relationship. – Lrodriguez84 Aug 31 '15 at 18:05
  • I suppose tbMenu1 is a complex object not a value type like String is. You should only take the information that you need from tbMenu1 and put it into diffenrent fields: label, url and so on. Hope it helps. – cristis Aug 31 '15 at 20:36
  • Thanks again cristis, tbMenu1 is unary relationship, and I need that relation, because could have more objects inside. I must load object by object to hand? could I load the linq object directly and send to jquery?. – Lrodriguez84 Sep 01 '15 at 11:57
  • You have to load everything manually from the start. You won't be able to navigate that property. You need to have a custom object that can hold all the data you have. – cristis Sep 01 '15 at 20:19