我在我的網絡應用程序,它可以是這樣創建一個表:如何創建數據表通過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