Lrodriguez84
Lrodriguez84

Reputation: 754

Convert Linq object to JsonResult in Mvc 4 using ajax

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!

Upvotes: 0

Views: 1184

Answers (1)

cristis
cristis

Reputation: 56

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.

Upvotes: 1

Related Questions