2010-02-05 32 views
10

Estoy tratando de usar la funcionalidad del lado del servidor del plugin jQuery Datatables con ASP.Net. La solicitud de ajax devuelve JSON válido, pero no aparece nada en la tabla.jQuery DataTables, procesamiento del lado del servidor y ASP.Net

Originalmente tuve problemas con los datos que estaba enviando en la solicitud de AJAX. Recibí un error de "primitivo JSON no válido". Descubrí que los datos deben estar en una cadena en lugar de ser serializados por JSON, como se describe en esta publicación: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/. No estaba muy seguro de cómo arreglar eso, así que traté de añadir esto en la solicitud Ajax:

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

Si las obras aboves finalmente voy a añadir los otros parámetros más tarde. En este momento solo intento que algo aparezca en mi mesa.

El JSON de retorno se ve bien y valida, pero el sEcho en la publicación no está definido, y creo que por eso no se cargan datos en la tabla.

Entonces, ¿qué estoy haciendo mal? ¿Estoy incluso en el camino correcto o estoy siendo estúpido? ¿Alguien se encontró con esto antes o tiene alguna sugerencia?

Aquí es mi 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 

devolverán como JSON:

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

Respuesta

3

Cambié la información a

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

y funcionó. Entonces, ahora la pregunta es cómo pasar el resto de los datos al servicio web. Intenté usar JSON2 para convertir el JSON en una cadena, pero eso abrió otra lata de gusanos, y es un problema aparte.

2

He estado trabajando en lo mismo y un amigo me ayudó con esta parte. Este código está en C#, pero debería poder portarlo.

código jQuery: Código

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

código detrás:

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

espero que esto ayude!

El siguiente paso para mí es trabajar en el filtrado, paginación y clasificación. Avíseme si obtiene estas piezas funcionando =)

+2

¿alguna vez consiguió el filtrado, paginación y clasificación para trabajar? –

3

Hay al menos dos problemas en su código javascript:

  1. "datos": "{ 'sEcho': '" + aoData [0] .Value + "'}",

Esto ya fue señalado por Chad. Esa es la forma correcta de obtener el sEcho:

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

Si está utilizando una versión reciente de .net (creo que 3.5 y superior) debe ajustar la función de éxito para regresar correctamente. Lee this para entender por qué tienes que pasar "msg.d".

Aquí está el código JS actualización:

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

Luego de conseguir este trabajo en el lado del servidor, no estoy seguro de lo que vas a tener que cambiar su código (ya que no soy una chico VB), pero sé que los siguientes trabajos para mí (utilizando un servicio web 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 clase "FormatedList" es simplemente para ayudar con el retorno JSON, convierten automáticamente porque estamos utilizando el ScriptService .

Cuestiones relacionadas