I have an MVC application and I need to draw tables from SQL on the Internet. I cannot create a table model in advance, so I dynamically create a DataTable using JavaScript code in a CSHTML file:
var data,tableName= '#demotable',
columns,
str,
jqxhr = $.ajax({
data: { str: JSON.stringify('kurator') },
"url": MyAppUrlSettings.MyUsefulUrl,
"type": "GET",
"datatype": "json"
})
.done(function () {
data = JSON.parse(jqxhr.responseText); debugger;
$.each(data.columns, function (k, colObj) {
str = '<th>' + colObj.data + '</th>';
$(str).appendTo(tableName + '>thead>tr'); debugger;
});
data.columns[0].render = function (data, type, row) {
return '<h4>' + data + '</h4>'; debugger;
}
$(tableName).dataTable({
"data": data.data,
"columns": data.columns,
"fnInitComplete": function () {
console.log('Datatable rendering complete');
}
}); debugger;
})
I need to return an array of JSON objects from ControllerAction. This is how I create my DataTable:
DataTable dt = new DataTable();
List<string> _columns = new List<string>() { "Kurator", "Filial", "Klient", "Saldo", "Docs", "no_Docs", "Change", "Status" };
for (int i = 0; i < _columns.Count; i++)
{
cols.Add(new Columns { ColumnID = "data", ColumnName = _columns[i] });
dt.Columns.Add(_columns[i], typeof(string));
}
DataRow _ravi;
_ravi = dt.NewRow();
dt.Rows.Add(_ravi);
Then finally, I need to put an array of columns and data in a JsonResult:
var data2 = debitor.Select(p => new {
Kurator = p.Kurator,
Filial = p.Filial,
Klient = p.Klient,
Saldo = p.Saldo,
Docs = p.Docs,
no_Docs = p.no_Docs,
Change = p.Change,
Status = p.Status
});
var columns = cols.Select(p => new {
data = p.ColumnName
});
return Json( new { data = data2, columns = columns} , JsonRequestBehavior.AllowGet);
This works correctly => it returns an array of objects (when from Model var data2), but when I try to get an array of strings from mine DataTable(commented), there are no results in Json.
How to fit JsonResultin lines DataTable? I can’t use the model because I don’t know how many columns there will be as a result of the SQL query.