1

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

<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# 代码以类似的方式填充表格?是否可以?我可以"mDataProp"像生成列一样在 Javascript 代码中生成行,但是如何在 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);

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

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

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

4

2 回答 2

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

});
于 2013-03-18T16:46:39.700 回答
0

我解决了我的问题。生成 JavaScript 比我想象的要容易。问题是,当我将 aoColumns 数组生成为 C# 字符串,然后将其分配给“aoColumns”属性时,如下所示:

"aoColumns": [
    @propertyStr
],

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

"aoColumns": [
    @Html.Raw(propertyStr)
],
于 2013-03-19T15:01:20.670 回答