2010-02-05 8 views
10

Je suis en train d'utiliser la fonctionnalité côté serveur du plugin jQuery DataTables avec ASP.Net. La requête ajax renvoie un JSON valide, mais rien n'apparaît dans la table.jQuery traitement côté serveur DataTables et ASP.Net

J'ai eu à l'origine des problèmes avec les données que j'envoyais dans la demande ajax. Je recevais une erreur "JSON primative non valide". J'ai découvert que les données doivent être dans une chaîne au lieu de JSON sérialisé, comme décrit dans cet article: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/. Je n'étais pas tout à fait sûr comment résoudre ce problème, donc j'ai essayé d'ajouter ceci dans la demande ajax:

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

Si les aboves fonctionne finalement, je vais ajouter les autres paramètres plus tard. En ce moment, j'essaie juste d'avoir quelque chose à montrer dans ma table.

Le retour JSON semble correct et valide, mais le sEcho dans le poste est indéfini, et je pense que c'est pourquoi aucune donnée est en cours de chargement dans la table.

Alors, qu'est-ce que je fais de mal? Suis-je même sur la bonne voie ou suis-je stupide? Est-ce que quelqu'un a rencontré cela avant ou avez-vous des suggestions?

Voici mon 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 

Returned JSON:

{"__type":"Data","sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[["testing","chad","testing"],["testing2","chad","testing"]]} 

Répondre

3

J'ai changé les données à

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

et cela a fonctionné. Alors maintenant, la question est de savoir comment transmettre le reste des données au webservice. J'ai essayé d'utiliser JSON2 pour transformer le JSON en chaîne, mais cela a ouvert une autre boîte de Pandore, et c'est un problème distinct.

2

Je travaille sur la même chose et un de mes amis m'a aidé avec cette partie. Ce code est en C# mais vous devriez pouvoir le porter.

Code 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> 

Code 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> 

code derrière:

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

J'espère que cela aide!

La prochaine étape pour moi est d'obtenir le filtrage, la pagination et le tri de travail. Faites-moi savoir si vous obtenez ces pièces de travail =)

+2

avez-vous déjà eu le filtrage, la pagination et le tri pour fonctionner? –

3

Il y a au moins deux questions dans votre code javascript:

  1. "données": "{ 'sEcho': '" + aoData [0] .Value + "'}",

Cela a déjà été souligné par le Tchad. C'est la bonne façon d'obtenir le sEcho:

  1. "success": function (msg) {fnCallback (msg.d); }

Si vous utilisez une version récente de .net (je crois 3.5 et plus), vous devez ajuster la fonction de succès pour retourner correctement. Lisez this pour comprendre pourquoi vous devez passer "msg.d".

Voici votre code js mise à jour:

$("#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); 
         } 
      }); 
     } 
    }); 

Ensuite, pour obtenir ce travail sur le côté serveur, je ne suis pas sûr de ce que vous devez changer dans votre code (car je ne suis pas type VB), mais je sais que les œuvres suivantes pour moi (en utilisant un webservice 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; } 
} 

la classe « FormatedList » est simplement d'aider le retour JSON, convertis automatiquement parce que nous utilisons la ScriptService .