Reputation: 9634
I am using Datatables grid in my MVC application to show the data. I'm not getting how to convert the Var which contains the generic list to JSON which in turn will be the input for Datatables.
Here is the JSON format for Datatables:
return Json(new
{
aaData = new[] {
new [] { "Trident", "Internet Explorer 4.0", "Win 95+", "4", "X" },
new [] { "Gecko", "Firefox 1.5", "Win 98+ / OSX.2+", "1.8", "A" },
new [] { "Webkit", "iPod Touch / iPhone", "iPod", "420.1", "A" },
}
}, JsonRequestBehavior.AllowGet);
But the above one is hardcoded one, I'm getting generic list in runtime, how to iterate and change to JSON format like above.
Here is my code.
public void GetReport()
{
var ReportData = _homeService.GetReportDatafromDB();
if (ReportData .Count > 0)
{
//Dont no how to convert for JSON data format here
}
}
Upvotes: 1
Views: 2437
Reputation: 3591
Using the foreach syntax it will look something like this:
var aaData = new List<string[]>();
foreach(var l in ReportData){
aaData.Add(new [] {l.Property1, l.Property2, l.Property3, l.Property4});
}
var thisIsYourResult = aaData.ToArray();
Upvotes: 3
Reputation: 3591
This is an example of how to get your desired format:
for the ease of the exercise lets use a "Model" as the data object class:
public class Model{
public string Property1{get;set;}
public string Property2{get;set;}
public string Property3{get;set;}
public string Property4{get;set;}
}
Then you just need to go over it and create your desired json structure:
var ReportData = new List<Model>{
new Model{Property1 = "Trident", Property2 = "Internet Explorer 4.0", Property3 = "Win 95+", Property4 = "4"},
new Model{Property1 = "Gecko", Property2 = "Firefox 1.5", Property3 = "Win 98+ / OSX.2+", Property4 = "1.8"}
};
var aaData = ReportData.Select(l => new [] {l.Property1, l.Property2, l.Property3, l.Property4} ).ToArray();
Upvotes: 1