Alexandre Lima Alexandre Lima - 4 months ago 15
C# Question

Return JSON data from with "data"

I need to populate a jQuery datatable with my database data, but was very difficult to do so. Searching in the web, I believe I have found the cause, which would be the json format returned by my controller. The format should be as follows:

{
"data": [
{
"ID": "1",
"CODIGO": "CC0050",
"TEXTO": "USINAGEM"
},
{
"ID": "2",
"CODIGO": "CC0100",
"TEXTO": "MONTAGEM"
}]
}


but are returning in this format:

[
{
"ID":24,
"CODIGO":"CC0050",
"TEXTO":"USINAGEM"
},
{
"ID":25,
"CODIGO":"CC0100",
"TEXTO":"MONTAGEM"
}
]


this is the controller code:

[HttpGet]
public JsonResult GetAllCECOS()
{
using (RPIEntities contextObj = new RPIEntities())
{
try
{
var listaCECOS = contextObj.T0CECOS.ToList();
return Json(listaCECOS, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{

throw ex;
}
}
}

Answer

the cause that you are returning the list of objects, and this is list actually parsed in JSON.

What you want is an actual object with the "data" property, as such:

public class MyReturningObject
{
    public IEnumerable<T0CECOS> data { get; set; }
}

or use an anonymous object:

return new { data = listaCECOS };

Add the list in this object and parse it in JSON for the actual awaited JSON!

{
  "data": [
    {
      "ID": "1",
      "CODIGO": "CC0050",
      "TEXTO": "USINAGEM"
    },
    {
      "ID": "2",
      "CODIGO": "CC0100",
      "TEXTO": "MONTAGEM"
    }]
}