By default, DataTables Ajax expects JSON data to be an array of arrays.
Using JSON.Net , you can serialize the collection into an array of arrays instead of an array of objects via an attribute / parameter or do it using a custom JsonConverter . The object I'm trying to serialize is as follows:
public class DeviceIndex { public int Id { get; set; } [Display(Name = "Asset Tag")] public string AssetTag { get; set; } [Display(Name = "Lease End")] [DataType(DataType.Date)] public DateTime LeaseEndDate { get; set; } public string Type { get; set; } [Display(Name = "Operating System")] public string OperatingSystem { get; set; } public string Model { get; set; } }
And my action with the controller is as follows:
public IActionResult IndexJson() { var model = _db.Devices.Select(d => new DeviceIndex { ... }).ToList(); return Content(JsonConvert.SerializeObject(new { data = model }), "application/json"); }
What JSON outputs:
{ "data": [ { "Id": 1649, ... }, { "Id": 703, ... } ] }
Although my desired results are as follows:
{ "data": [ [ "1649", ... ], [ "703", ... ] ] }
I thought I could use the JsonArray attribute for my collection, but didn't want to change the output.
[JsonArray] public class DevicesIndex: IEnumerable<DeviceIndex> { List<DeviceIndex> devices; public IEnumerator<DeviceIndex> GetEnumerator() { return devices.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
source share