0

我想知道如何在 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;

    }
4

4 回答 4

1

我假设您想将数据表转换为 json?如果我错了,请纠正我。您可以使用 json.net 库来做到这一点:

http://james.newtonking.com/projects/json-net.aspx

string json = JsonConvert.SerializeObject(table, Formatting.Indented);
于 2013-06-06T09:08:54.937 回答
1

试试下面的 JsonResult,它应该以数据表插件期望的格式返回结果。

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"
        },
    ]
}
于 2013-06-07T13:46:18.823 回答
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;
    }
于 2013-06-07T14:44:10.130 回答
0

对我来说,这个工作:

return Json(new {
                    aaData = Json(list).Data
                },
                "application/json", JsonRequestBehavior.AllowGet);
于 2013-07-02T15:05:37.927 回答