Ahmad Ahmad Ahmad Ahmad - 1 month ago 13
JSON Question

How to building JSON result C#,MVC?

I have this data

data

and want to return it like

json

I wrote this code

[HttpGet]
public JsonResult GetTime()
{
var data = _db.CourseTimes.Select(c => new { c.Day, c.StartTime, c.EndTime })
.GroupBy(c=>c.Day).ToList();

return Json(data, JsonRequestBehavior.AllowGet);
}

Answer

Try this

[HttpGet]
public JsonResult GetTime()
{
     var data = _db.CourseTimes
         .GroupBy(c => c.Day)
         .ToDictionary(g => g.Key, v => v.Select(c => new { start = c.StartTime, stop = c.EndTime }));

    return Json(data, JsonRequestBehavior.AllowGet);
}

Group by the day and use a dictionary with day as key to get the expected format you wanted.

Comments