I run a query that returns me a list of customers orders:
SELECT cust_no, cust_name, order_no, order_name FROM CustomerOrders
In my Controller Action
method, I do the following (_context
is my DataContext
):
var results = _context.CustomerOrders.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
When I inspect this in the debugger, I see the list of objects, but not being too familiar with Json, I am not sure how this would look when it as a Json string. The format I want is:
{
"Customer": {
"cust_no": "123",
"cust_name": "john",
"Orders": [
{
"order_no": "1",
"order_name": "order1"
},
{
"order_no": "2",
"order_name": "order2"
}
]
},
"Customer": {
"cust_no": "456",
"cust_name": "jane",
"Orders": [
{
"order_no": "3",
"order_name": "order3"
},
{
"order_no": "4",
"order_name": "order4"
}
]
}
}
I currently can get into this:
{ Customer = "123", cust_name = "John", Orders = "1", oder_no = "order1" }
with:
_context.CustomerOrders.Select(x => new
{
Customer= x.cust_no, x.cust_name,
Orders = x.order_no, x.order_name});
public ActionResult GetCustomerOrders()
{
JsonResult result = null;
try
{
var results = new {Customers = _context.CustomerOrders.ToList()};
return Json(results,JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//Log
}
return result;
}