我在我的网络应用程序,它可以是这样创建一个表:如何创建数据表通过JSON充满时列数是未知
<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" },
}
}
],
但它不起作用。我该怎么做?
使你拥有了JSON字符串包含数据的行,但你不知道有多少列的每一行,我是正确? – 2013-03-18 16:45:53
我的意思是以下行中的标识符:Column1 = str +“1”,Column2 = str +“2”...匹配JS代码中的字符串({“mDataProp”:“Column1”} ...)。我可以像这样为n列生成n个JS行:@ {for(int i = 0; i <10; ++ i){“mDataProp”:“Column”+ @i}}。但是我不能以类似的方式“生成”C#代码。 – 2013-03-18 23:13:32