C#MVC JsonResult动态数据表

时间:2016-12-05 09:00:08

标签: javascript c# json asp.net-mvc datatable

我有一个MVC应用程序,我需要从SQL绘制表到Web。我无法预先创建表的模型,因此我在CSHTML文件中使用JavaScript代码动态创建DataTable:

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;
    });

我需要从ControllerAction返回一个JSON对象数组。这就是我创建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);

然后,最后,我需要将列和数据的数组放入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);

这正常工作=&gt;它返回一个对象数组(当来自Model var data2时),但是当我尝试从我的DataTable(注释)中获取行数时,Json中没有结果。

如何正确地将JsonResult放入我的DataTable行?我不能使用模型,因为我不知道SQL查询结果中有多少列。

1 个答案:

答案 0 :(得分:0)

从我的角度来看,这个问题有些复杂。

如果您使用Microsoft.AspNetCore.Mvc JsonResult类,则将根据输入参数产生以下结果:

List<>一起使用时:

 using Microsoft.AspNetCore.Mvc;

 class SomeClass 
 {
     public string value1 {get; set;}
     public int value2 {get; set;}
 }

 // Controller code
 List<SomeClass> result = // Init list using Linq Select or similar
 return new JsonResult(result);

此代码像这样(对象数组)产生JSON

{
     [
          { value1: "some string",
            value2: 1
          },
          {
            value1: "another string",
            value2: 20
          }
     ]
}

Dictionary<>一起使用

class AnotherClass 
{
    public string value1 {get; set;}
    public int value2 {get; set;}
}

// Controller code
// Dictionary should has key which became key in resulting object
Dictionary<string, AnotherClass> result = // Init dictionary 
return new JsonResult(result);

此代码像这样(一个大对象)生成JSON。 “ key1”和“ key2”是字典中的键。

{
     key1: { 
               value1: "some string",
               value2: 1
           },
     key2: {
               value1: "another string",
               value2: 20
          }
}