10

我正在尝试将 jQuery Datatables 插件的服务器端功能与 ASP.Net 一起使用。ajax 请求返回有效的 JSON,但表中没有显示任何内容。

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

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

如果上述方法最终有效,我稍后会添加其他参数。现在我只是想让一些东西出现在我的桌子上。

返回的 JSON 看起来没问题并且可以验证,但是帖子中的 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()> _
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

4 回答 4

4

我将数据更改为

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

它奏效了。所以现在的问题是如何将其余数据传递给 web 服务。我尝试使用 JSON2 将 JSON 转换为字符串,但这打开了另一个蠕虫罐,并且是一个单独的问题。

于 2010-02-05T21:43:19.077 回答
3

您的 javascript 代码中至少存在两个问题:

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

乍得已经指出了这一点。这是获取 sEcho 的正确方法:

  1. “成功”:函数(msg){ fnCallback(msg.d);}

如果您使用的是最新版本的 .net(我相信 3.5 及更高版本),您需要调整成功函数以正确返回。阅读本文以了解为什么您必须通过“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,所以会自动转换。

于 2011-03-01T20:26:01.503 回答
2

我一直在做同样的事情,我的一个朋友帮助我完成了这部分。此代码在 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>

asp代码:

<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;
    }

我希望这有帮助!

对我来说,下一步是让过滤、分页和排序工作。让我知道你是否让这些部件正常工作 =)

于 2010-06-15T19:51:19.437 回答
2

您可能想在这里查看 zowen 的解决方案http://weblogs.asp.net/zowens/archive/2010/01/19/jquery-datatables-plugin-meets-c.aspx。他完成了一个运行良好的数据表解析器。

希望这可以帮助。

于 2010-09-28T13:36:53.407 回答