C # MVC JsonResult dynamic datatable

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;
                // Iterate each column and print table headers for Datatables
                $.each(data.columns, function (k, colObj) {
                    str = '<th>' + colObj.data + '</th>';
                    $(str).appendTo(tableName + '>thead>tr'); debugger;
                });
                // Add some Render transformations to Columns
                // Not a good practice to add any of this in API/ Json side
                data.columns[0].render = function (data, type, row) {
                    return '<h4>' + data + '</h4>'; debugger;
                }
                        // Debug? console.log(data.columns[0]);
                $(tableName).dataTable({
                    "data": data.data,
                    "columns": data.columns,
                    "fnInitComplete": function () {
                        // Event handler to be fired when rendering is complete (Turn off Loading gif for example)
                        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));
            }

// Add rows to Table

            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 data1 = JsonConvert.DeserializeObject(data);

                //   var data = new JavaScriptSerializer().Serialize(dt, Formatting.Indented);

               // JObject rss =  new JObject(new JProperty("title", "James Newton-King"));

                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.

+4

Source: https://habr.com/ru/post/1662818/


All Articles