DataTable to Json using jquery

前端 未结 9 1206
抹茶落季
抹茶落季 2020-12-16 05:48

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

$.ajax({  
    type: \"POST\",  
    url: url,  
    data: d         


        
相关标签:
9条回答
  • 2020-12-16 06:17

    It works for very well for me with a WebService

        Imports System.Web.Script.Serialization
    
        Dim wsServicio As New ["YourWsInstance"]
        Dim dsInstEstado As New DataSet
        Dim sSql As String
    
        sSql = " Your SQL Statement"
        dsInstEstado = wsServicio.getData("YourWebServiceParameters")
        Dim jsonString = DataTableToJSON(dsInstEstado.Tables("CA_INSTITUCION"))
        Return Json(jsonString, JsonRequestBehavior.AllowGet)
    
        Function DataTableToJSon(dt As DataTable) As Object
        Dim arr(dt.Rows.Count - 1) As Object
        Dim column As DataColumn
        For i = 0 To dt.Rows.Count - 1
            Dim dict As New Dictionary(Of String, Object)
            For Each column In dt.Columns
                dict.Add(column.ColumnName, dt.Rows(i)(column))
            Next
            arr(i) = dict
        Next
       Return arr
     End Function
    
    0 讨论(0)
  • 2020-12-16 06:17

    I found this C# class very useful:

    [Serializable]
    public class TableMethod
    {
        private int m_total; public int total { get { return this.m_total; } set { this.m_total = value; } }
        private int m_page; public int page { get { return this.m_page; } set { this.m_page = value; } }
        private int m_records; public int records { get { return this.m_records; } set { this.m_records = value; } }
        private IList<RowElement> m_rows; public IList<RowElement> rows { get { return this.m_rows; } set { this.m_rows = value; } }
        public TableMethod()
        {
            this.m_records = 20;
            this.m_total = 20;
            this.m_page = 1;
        }
    }
    [Serializable]
    public class RowElement
    {
        public string id;
        public string[] cell;
    }
    
    0 讨论(0)
  • 2020-12-16 06:21

    Like Marc, I too am not surprised that the DataTable breaks your webservice/json exchange. I'd like to endorse Json.NET also.

    But if you decide to not go with it, you still don't have to build the json manually. Just make your own lean custom class with all the properties you need and then return an array of that class. You will of course have to write code to "convert" your data table into your new class. I know, it could be a lot of code writing, but it's a lot less error prone then trying to manually make a json string.

    0 讨论(0)
提交回复
热议问题