数据表来使用jquery的Json [英] DataTable to Json using jquery

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

问题描述

我试图执行它返回一​​个DataTable与下面这段code 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  
        }  
    }); 

如果该Web服务返回一个类,那么它的工作原理,因此没有任何与输入paramters等,只有当Web方法返回一个数据表(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。它似乎并没有与数据表工作。

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

推荐答案

在最后,我决定用JavaScriptSerializer类到DataTable转换成JSON字符串。 遗憾的是,我转换数据表为dictionnaries名单此类不正常工作与数据表和列表传递给JavaScriptSerializer类。它采用了code只有几行,它工作正常。
例如,在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

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

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