DataTable到Json使用jquery [英] DataTable to Json using jquery

查看:135
本文介绍了DataTable到Json使用jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一个Web服务,它返回一个数据表,其代码如下:

I'm trying to execute a web service which returns a DataTable with the following piece of code:

$.ajax({  
    type: "POST",  
    url: url,  
    data: data,   
    contentType: "application/json; charset=utf-8",  
    dataType: "json",  
    success: function(msg) {  
        //do things  
        }  
    }); 

如果webservice返回一个类,那么它的工作原理与输入参数无关。当Web方法返回一个datatable(datatable只有2列,2行为测试我在做)时,它只会失败。

If the webservice returns a class then it works so it has nothing to do with the input paramters etc. It only fails when the web method returns a datatable (the datatable only has 2 columns and 2 rows for the test I'm doing).

WebService类用[ScriptService]属性,所以我认为ASP.NET会自动将返回值序列化为JSON。它似乎不适用于datatable。

The WebService class is decorated with the [ScriptService] attribute so I thought that ASP.NET would automatically serialize the return value as JSON. It doesn't seem to work with datatable.

我发现唯一的解决方案是返回一个字符串(手动的JSON序列化对象),但它似乎不对我来说,这样做。

我使用Visual Studio 2008与.Net 3.5

The only solution I've found was to return a string (a manually JSON serialized object) but it doesn't seem right to me to do it this way.
I'm using Visual Studio 2008 with .Net 3.5

推荐答案

p>最后,我决定使用JavaScriptSerializer类将DataTable转换为JSON字符串。
不幸的是,此类不适用于DataTable,因此我将DataTable转换为词典列表,并将该列表传递给JavaScriptSerializer类。它只需要几行代码,它的工作正常。

VB.net中的示例:

In the end, I've decided to use the JavaScriptSerializer class to convert the DataTable into a JSON string. Unfortunately, this class doesn't work with a DataTable so I converted the DataTable into a list of dictionnaries and pass that list to the JavaScriptSerializer class. It takes only a few lines of code and it works fine.
Example in VB.net:

    Public Function GetJson(ByVal dt As DataTable) As String

        Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
        Dim rows As New List(Of Dictionary(Of String, Object))
        Dim row As Dictionary(Of String, Object)

        For Each dr As DataRow In dt.Rows
            row = New Dictionary(Of String, Object)
            For Each col As DataColumn In dt.Columns
                row.Add(col.ColumnName, dr(col))
            Next
            rows.Add(row)
        Next
        Return serializer.Serialize(rows)
    End Function

这篇关于DataTable到Json使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆