我想知道如何在asp.net mvc 4应用程序中将数据传递给datatable.net。
就像这个例子: http://www.datatables.net/release-datatables/examples/data_sources/ajax.html
我想要的输出格式是这样的,但我无法弄清楚如何产生这个结果:
{
"aaData": [
[
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
],
[
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
]
]
}
到目前为止,我有这样的事情:
public JsonResult GetDataList(int? assetId)
{
var tableData = DBData.ToList();
var res = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = ??? // I must do something here with tableData
};
return res;
}
答案 0 :(得分:1)
尝试下面的JsonResult,它应该以datatables插件所期望的格式返回结果。
public JsonResult GetDataList(int? assetId)
{
var tableData = DBData.ToList();
return Json(new {
aaData = ???
},
"application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
这应该返回你的Json如下:
{
"aaData": [
{
"Trident",
"Internet Explorer 4.0",
"Win 95+",
"4",
"X"
},
{
"Trident",
"Internet Explorer 5.0",
"Win 95+",
"5",
"C"
},
]
}
答案 1 :(得分:1)
我想通了,我的问题是我必须使用一个对象数组(object []),而不是列表
public JsonResult GetData(int? Id)
{
List<sp_data_R_Result> tableData;
if (assetId != null)
tableData = DBData.Where(x => x.Id== Id).ToList();
else
tableData = DBData.ToList();
var res = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
aaData = from d in tableData
select new object[]
{
d.col1,
d.col2,
...
}
}
};
return res;
}
答案 2 :(得分:0)
我假设您想将数据表转换为json?如果我错了,请纠正我。你可以使用json.net库来实现它:
http://james.newtonking.com/projects/json-net.aspx
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
答案 3 :(得分:0)
对我来说,这个有用:
return Json(new {
aaData = Json(list).Data
},
"application/json", JsonRequestBehavior.AllowGet);