代码之家  ›  专栏  ›  技术社区  ›  Chad

jquery数据表服务器端处理与asp.net

  •  10
  • Chad  · 技术社区  · 15 年前

    我正在尝试将jquery datatables插件的服务器端功能与asp.net结合使用。ajax请求返回有效的json,但表中没有显示任何内容。

    我最初在ajax请求中发送的数据有问题。我收到一个“无效的json主”错误。我发现数据需要用字符串而不是json序列化,如本文所述: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/ . 我不太确定如何修复它,所以我尝试在ajax请求中添加这个:

    "data": "{'sEcho': '" + aoData.sEcho + "'}"
    

    如果上述方法最终有效,我稍后将添加其他参数。现在我只是想弄点东西来摆在我的桌子上。

    返回的json看起来没问题,并且是有效的,但是post中的secho是未定义的,我想这就是为什么没有数据被加载到表中的原因。

    那么,我做错什么了?我是在正确的轨道上还是在愚蠢?以前有没有人碰到过这个问题,或者有什么建议?

    这是我的jquery:

    $(document).ready(function()
    {
    
        $("#grid").dataTable({
                "bJQueryUI": true,
                "sPaginationType": "full_numbers",
                "bServerSide":true, 
                "sAjaxSource": "GridTest.asmx/ServerSideTest", 
                "fnServerData": function(sSource, aoData, fnCallback) {
                   $.ajax({
                        "type": "POST",
                        "dataType": 'json',
                        "contentType": "application/json; charset=utf-8",
                        "url": sSource, 
                        "data": "{'sEcho': '" + aoData.sEcho + "'}",
                        "success": fnCallback
                    });
               }
             });
    
    
     });
    

    HTML:

    <table id="grid">
       <thead>
          <tr>
             <th>Last Name</th>
             <th>First Name</th>
             <th>UserID</th>
           </tr>
        </thead>
    
        <tbody>
           <tr>
        <td colspan="5" class="dataTables_empty">Loading data from server</td>
           </tr>
        </tbody>
     </table>
    

    Webmethod:

     <WebMethod()> _
    Public Function ServerSideTest() As Data
    
    
        Dim list As New List(Of String)
        list.Add("testing")
        list.Add("chad")
        list.Add("testing")
    
        Dim container As New List(Of List(Of String))
        container.Add(list)
    
        list = New List(Of String)
        list.Add("testing2")
        list.Add("chad")
        list.Add("testing")
    
        container.Add(list)
    
        HttpContext.Current.Response.ContentType = "application/json"
    
        Return New Data(HttpContext.Current.Request("sEcho"), 2, 2, container)
    
    End Function
    
    
    Public Class Data
    Private _iTotalRecords As Integer
    Private _iTotalDisplayRecords As Integer
    Private _sEcho As Integer
    Private _sColumns As String
    Private _aaData As List(Of List(Of String))
    
    Public Property sEcho() As Integer
        Get
            Return _sEcho
        End Get
        Set(ByVal value As Integer)
            _sEcho = value
        End Set
    End Property
    
    Public Property iTotalRecords() As Integer
        Get
            Return _iTotalRecords
        End Get
        Set(ByVal value As Integer)
            _iTotalRecords = value
        End Set
    End Property
    
    Public Property iTotalDisplayRecords() As Integer
        Get
            Return _iTotalDisplayRecords
        End Get
        Set(ByVal value As Integer)
            _iTotalDisplayRecords = value
        End Set
    End Property
    
    
    
    Public Property aaData() As List(Of List(Of String))
        Get
            Return _aaData
        End Get
        Set(ByVal value As List(Of List(Of String)))
            _aaData = value
        End Set
    End Property
    
    Public Sub New(ByVal sEcho As Integer, ByVal iTotalRecords As Integer, ByVal iTotalDisplayRecords As Integer, ByVal aaData As List(Of List(Of String)))
        If sEcho <> 0 Then Me.sEcho = sEcho
        Me.iTotalRecords = iTotalRecords
        Me.iTotalDisplayRecords = iTotalDisplayRecords
        Me.aaData = aaData
    End Sub
    

    返回的JSON:

    {"__type":"Data","sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[["testing","chad","testing"],["testing2","chad","testing"]]}
    
    4 回复  |  直到 13 年前
        1
  •  4
  •   Chad    15 年前

    我把数据改成

    "data": "{'sEcho': '"+ aoData[0].value + "'}",
    

    而且成功了。所以现在的问题是如何将剩余的数据传递给webservice。我试着使用json2将json转换成字符串,但这又打开了另一个漏洞,这是一个单独的问题。

        2
  •  3
  •   Wagner Danda da Silva Filho    13 年前

    javascript代码中至少有两个问题:

    1. “data”:“{'secho':'”+aodata[0].value+“'}”,

    乍得已经指出了这一点。这是得到塞科的正确方法:

    1. “success”:函数(msg){fncallback(msg.d);}

    如果您使用的是最新版本的.NET(我相信是3.5及更高版本),则需要调整success函数才能正确返回。读 this 为了理解为什么你必须传递“msg.d”。

    以下是您更新的js代码:

    $("#grid").dataTable({
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "bServerSide":true, 
            "sAjaxSource": "GridTest.asmx/ServerSideTest", 
            "fnServerData": function(sSource, aoData, fnCallback) {
               $.ajax({
                    "type": "POST",
                    "dataType": 'json',
                    "contentType": "application/json; charset=utf-8",
                    "url": sSource, 
                    "data": "{'sEcho': '" + aoData[0].value + "'}",
                    "success": function (msg) {
                                fnCallback(msg.d);
                            }
                });
           }
         });
    

    为了让这个在服务器端工作,我不确定您需要在代码中更改什么(因为我不是vb人员),但我知道以下对我有效(使用asmx webservice):

    using System;
    using System.Web;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    using System.Collections.Generic;
    
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class GridTest : System.Web.Services.WebService
    {
    
        [WebMethod]
        public FormatedList ServerSideTest(string sEcho)
        {
            var list = new FormatedList();
    
            list.sEcho = sEcho;
            list.iTotalRecords = 1;
            list.iTotalDisplayRecords = 1;
    
            var item = new List<string>();
            item.Add("Gecko");
            item.Add("Firefox 1.0");
            item.Add("Win 98+ / OSX.2+");
            item.Add("1.7");
            item.Add("A");
            list.aaData = new List<List<string>>();
            list.aaData.Add(item);
    
            return list;
        }
    
    }
    
    public class FormatedList
    {
        public FormatedList()
        {
        }
        public string sEcho { get; set; }
        public int iTotalRecords { get; set; }
        public int iTotalDisplayRecords { get; set; }
        public List<List<string>> aaData { get; set; }
    }
    

    类“formatedlist”只是为了帮助json返回,它是自动转换的,因为我们使用的是scriptservice。

        3
  •  2
  •   Solburn    14 年前

    我一直在做同样的事情,我的一个朋友帮我完成了这部分。这段代码是用c编写的,但您应该能够将它移植过来。

    jQuery代码:

    <script type="text/javascript">
            $(document).ready(function() {
                function renderTable(result) {
                    var dtData = [];
                    // Data tables requires all data to be stuffed into a generic jagged array, so loop through our
                    // typed object and create one.
                    $.each(result, function() {
                        dtData.push([
                               this.FirstName,
                               this.LastName,
                               this.Sign
                            ]);
                    });
    
                    $('#grid').dataTable({
                        'aaData': dtData,
                        "bJQueryUI": true
                    });
                }
    
                // Make an AJAX call to the PageMethod in the codebehind
                $.ajax({
                    url: '<%= Request.Url.AbsolutePath %>/ServerSideTest',
                    data: '{}',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function(result) {
                        // Call the renderTable method that both fills the aaData array with data and initializes the DataTable.
                        renderTable(result.d);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest + ": " + textStatus + ": " + errorThrown);
                    }
                });
            });
        </script>
    

    ASPX代码:

    <table id="grid" width="100%">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Sign</th>
                </tr>
            </thead>
    
            <tbody>
                <tr>
                    <td colspan="5" class="dataTables_empty">Loading data from server</td>
                </tr>
            </tbody>
        </table>
    

    代码后面:

    // to serialize JSON in ASP.NET, it requires a class template.
        [Serializable]
        public class Data
        {
            // Yay for 3.5 auto properties
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Sign { get; set; }
        };
    
        [WebMethod]
        public static List<Data> ServerSideTest()
        {
            List<Data> DataList = new List<Data>();
    
            Data thisData = new Data();
            thisData.FirstName = "Sol";
            thisData.LastName = "Hawk";
            thisData.Sign = "Aries";
    
            DataList.Add(thisData);
    
            Data thisData2 = new Data();
            thisData2.FirstName = "Mako";
            thisData2.LastName = "Shark";
            thisData2.Sign = "Libra";
    
            DataList.Add(thisData2);
    
            return DataList;
        }
    

    我希望这有帮助!

    我的下一步是让过滤、分页和排序工作。让我知道如果你让这些零件工作的话=)

        4
  •  2
  •   Izmoto    14 年前

    你也许想看看佐文的解决方案 http://weblogs.asp.net/zowens/archive/2010/01/19/jquery-datatables-plugin-meets-c.aspx . 他做了一个很好的数据表解析器。

    希望这有帮助。