当列数未知时,如何创建由JSON填充的DataTable

时间:2013-03-18 16:37:20

标签: json asp.net-mvc-3

我的网络应用程序中有一个表,它是这样创建的:

<table id="mygrid">
    <thead>
        <th>Col1</th>
        <th>Col2</th>
        <th>Col3</th>
    </thead>
</table>
<script type="text/javascript">
    $(document).ready(function() {
        window.oTable = $("#mygrid").dataTable({
            "bServerSide": true,
            "bSort": false,
            "sAjaxSource": "@Url.Action("MyFunction", "Events")",
            "fnServerParams": function(aoData) {
                aoData.push({ name: "arg1", value: "@Model.arg1" });
            },
            "aoColumns": [
                { "mDataProp": "Column1" },
                { "mDataProp": "Column2" },
                { "mDataProp": "Column3" }
            ],
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "bProcessing": false
        });

我用返回JSON结果的函数填充它,如下所示:

ActionResult MyFunction(string arg1, ...)
{
    List<string> someList = ...;
    object array = eventsList.Select(str => new
    {
        Column1 = str + "1",
        Column2 = str + "2",
        Column3 = str + "3"
    });

    var result = new
    {
        sEcho = ...,
        iTotalRecords = ...,
        iTotalDisplayRecords = ...,
        aaData = array
    };

    return Json(result, JsonRequestBehavior.AllowGet);
}

现在我想动态生成表,所以我不知道设计时的列数。例如:

<table id="mygrid"><thead>
    @{
        foreach (string col in colNames)
            <th>@col</th>
    }
</thead></table>

请问您应该如何更改我的Javascript和C#代码以类似的方式填写表格?可能吗?我可以在Javascript代码中生成"mDataProp"行,就像我生成列一样,但是如何在C#代码中创建JSON结果?

加了:

我用控制器解决了这个问题。正如我发现的那样,字典列表被序列化为与匿名对象列表完全相同的JSON,所以我写了这个:

for (int i = 0; i < n; ++i)
{
    list.Add(new Dictionary<string, string>());
    foreach (int colName in colNames) events[i][colName] = cellValue;
}
var result = new 
{
    ...,
    aaData = list
};
return Json(result, JsonRequestBehavior.AllowGet);

现在我有了新的问题。我无法使用C#循环生成“aoColumns”数组,就像我在HTML代码中生成标签一样。我试过这样:

"aoColumns": [
    @{
        for (int i = 0; i < n; ++i)
        {
            string colName = "Column" + i.ToString();
            { "mDataProp": "@colName" },
        }
    }
],

但它不起作用。我该怎么办?

2 个答案:

答案 0 :(得分:1)

DataTables不允许动态更改列,但您可以在数据之前获取列并在其回调函数上加载数据表...

$.ajax('url/columns', function(data){

   //write table header

var options =   
"bProcessing": true, 
"bServerSide": true, 
"sAjaxSource": getGridDataUrl, 
"iDisplayLength": 10,
"aoColumns": //column settingssss
};
    $('#myDataTable').dataTable(options);

});

答案 1 :(得分:0)

我解决了我的问题。我认为生成JavaScript更容易。问题是,当我将aoColumns数组生成为C#字符串,然后将其分配给“aoColumns”属性时,这样:

"aoColumns": [
    @propertyStr
],

编译器以某种方式隐藏了引号和括号。 正确的方法是这样做:

"aoColumns": [
    @Html.Raw(propertyStr)
],