【问题标题】:jQuery DataTables server side processing and ASP.NetjQuery DataTables 服务器端处理和 ASP.Net
【发布时间】:2011-01-13 16:32:01
【问题描述】:

我正在尝试将 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 看起来没问题并且可以验证,但是帖子中的 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"]]}

【问题讨论】:

    标签: jquery-plugins webforms asp.net-2.0 datatables


    【解决方案1】:

    我把数据改成

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      如果您使用的是最新版本的 .net(我相信是 3.5 及更高版本),您需要调整成功函数以正确返回。阅读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 网络服务):

      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】:

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

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

          希望这会有所帮助。

          【讨论】:

          • +1 用于分享与问题相关的链接。我发现该链接对我的案例非常有帮助。谢谢。
          猜你喜欢
          • 2021-05-21
          • 2011-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多