我的网络应用程序中有一个表,它是这样创建的:
<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" },
}
}
],
但它不起作用。我该怎么做?