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

Asked

Viewed 471 times

0

I have 3 classes being 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 data-column-id="Unit.Name"

Class Contact

 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; }
}

Class Unit

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

Sector 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 controller’s Return 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 get Json to come all at the same level?

[{
  ContatoID: 4,
  Nome: "Luiz",
  Ramal: "9500",
  UnidadeID: 1,
  NomeUnidade: "Oeste Paulista Setor 1"
}]

2 answers

1


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

You can create an anonymous type or create a class to represent this type.

Using LINQ is very 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); 

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 you can join between the tables using the Entity framework itself.

And to return you can use the

return Json( lista, AllowGet); 

Browser other questions tagged

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