2010-02-05 30 views
10

Sto provando a utilizzare la funzionalità lato server del plugin jQuery Datatables con ASP.Net. La richiesta Ajax restituisce JSON valido, ma nella tabella non compare nulla.jQuery DataTables elaborazione lato server e ASP.Net

Originariamente avevo problemi con i dati che stavo inviando nella richiesta Ajax. Stavo ricevendo un errore "primitivo JSON non valido". Ho scoperto che i dati devono essere in una stringa anziché in JSON serializzati, come descritto in questo post: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/. Non ero del tutto sicuro come risolvere il problema che, così ho provato ad aggiungere questo nella richiesta Ajax:

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

Se i aboves fine lavori io aggiungo gli altri parametri in seguito. In questo momento sto solo cercando di ottenere qualcosa da mostrare nel mio tavolo.

Il JSON restituito sembra ok e convalida, ma il sEcho nel post non è definito, e penso che questo sia il motivo per cui nessun dato viene caricato nella tabella.

Quindi, cosa sto sbagliando? Sono sulla buona strada o sono stupido? Qualcuno si è imbattuto in questo prima o ha qualche suggerimento?

Ecco la mia 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 

restituito JSON:

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

risposta

3

Ho cambiato i dati in

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

e ha funzionato. Quindi ora la domanda è come passare il resto dei dati al webservice. Ho provato a usare JSON2 per trasformare il JSON in una stringa, ma questo ha aperto un'altra lattina di worm, ed è un problema separato.

2

Ho lavorato sulla stessa cosa e un mio amico mi ha aiutato con questa parte. Questo codice è in C# ma dovresti essere in grado di portarlo via.

codice jQuery: Codice

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

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

dietro:

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

Spero che questo aiuta!

Il prossimo passo per me è ottenere il filtraggio, il paging e l'ordinamento. Fatemi sapere se ottenete che queste parti funzionino =)

+2

hai mai ottenuto il filtraggio, il paging e l'ordinamento per funzionare? –

3

Ci sono almeno due problemi nel codice javascript:

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

Questo è stato già indicato dal Ciad. Questo è il modo giusto per ottenere il sEcho:

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

Se si utilizza una versione recente di .net (credo in 3,5 e versioni successive) è necessario regolare la funzione di successo per restituire correttamente. Leggi this per capire perché devi passare "msg.d".

Ecco il tuo codice js aggiornamento:

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

Poi, per ottenere questo lavoro sul lato server, non sono sicuro di quello che dovrete cambiare nel codice (dato che non sono un VB ragazzo), ma so che le seguenti opere per me (utilizzando 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" è semplicemente quello di aiutare con il ritorno jSON, convertiti automaticamente, perché stiamo usando la ScriptService .

Problemi correlati