How to leave the json of two or more object classes at the same level in Asp.Net MVC

0

I have 3 classes being them Contact, Sector, Unit so I have Contact with one-to-many relationship with Sector and Unit generating Json with many layers, making it impossible for JQuery Bootgrid to access these fields.

Checking JQuery Bootgrid documentation I noticed that it does not support the data-column-id="Drive.Name"

Contact Class

 public class Contato
{
    [Key]
    public int ContatoID { get; set; }
    public string Nome { get; set; }

    public int UnidadeID { get; set; }
    public Unidade Unidade { get; set; }

    public int SetorID { get; set; }
    public Setor Setor { get; set; }
}

Drive Class

 public class Unidade
{
    [Key]
    public int UnidadeID { get; set; }
    public string Nome { get; set; }
}

Industry Class

public class Setor
{
    [Key]
    public int SetorID { get; set; }
    public string Nome { get; set; }
}

These classes are generating the following JSON

rows: [
{
ContatoID: 4,
Nome: "Luiz",
UnidadeID: 1,
          Unidade: {
                    UnidadeID: 1,
                    Nome: "Oeste Paulista Setor 1"
           },
}

The return of the Controller responsible for returning Json is this

return Json(new {
   rows = contatosPaginados.ToList(),
   current = current,
   rowCount = rowCount,
   total = total
}, JsonRequestBehavior.AllowGet); 

The question is how do I make Json come all on the same level?

[{
  ContatoID: 4,
  Nome: "Luiz",
  Ramal: "9500",
  UnidadeID: 1,
  NomeUnidade: "Oeste Paulista Setor 1"
}]
    
asked by anonymous 24.02.2017 / 00:24

2 answers

1

Creating a new object with all the properties of the internal objects.

It is possible to create an anonymous type or create a class to represent this type.

Using LINQ is pretty easy.

var dados = contatosPaginados
                        .ToList()
                        .Select(c => new 
                               { 
                                   ContatoID = c.contatoID,
                                   Nome = c.Nome,
                                   UnidadeID = c.Unidade.UnidadeID,
                                   NomeUnidade = c.Unidade.Nome
                               }).ToList();

return Json(new { rows = dados, current = current, rowCount = rowCount, total = total }, 
            JsonRequestBehavior.AllowGet); 
    
24.02.2017 / 02:54
1
public class DaoContato {
    public int ContatoID {get;set;}
    public string Nome {get;set;}
    public int Ramal {get;set;}
    public int UnidadeID {get;set;}
    public int NomeUnidade {get;set;}
 }

  List< DaoContato > lista =  TABELA.Select(x=> new DaoContato () { ContatoID = x.ContatoID, Nome = x.Nome .... }

If you need to, you can JOIN between tables using the entity framework itself.

And to return you can use

return Json( lista, AllowGet); 
    
24.02.2017 / 14:57