2010-10-12 13 views
5

Estoy intentando llenar un jqGrid con datos de un servicio web. He revisado a fondo el código jqGrid y la documentación. Necesito otro par de ojos para mirar el siguiente código y decirme si me falta algo.jqGrid no se llena con datos

Como se verá en el código, tengo la red creada para carga cuando se carga la página o durante una actualización. Después de cargar la grilla, hago una llamada Ajax para obtener los datos JSON (nuevamente) y mostrarlos en un div debajo de la grilla.

que ver la mayor parte del comportamiento esperado. Después de cargar la página, la cuadrícula muestra el indicador de carga, luego se inicia la llamada Ajax y los datos JSON se muestran debajo de la cuadrícula. El problema es que la grilla está completamente vacía. Los encabezados de las columnas son correctos, pero no aparecen datos en el cuerpo de la cuadrícula.

Aquí está el código:

$(document).ready(function() { 
    $('#resultDiv').html(''); 
    $('#waitIndicator').hide(); 
    $("#list").jqGrid({ 
     datatype: 'json', 
     url: 'WeatherDataService.svc/GetWeatherData', 
     jsonReader: { 
      root: "Rows", 
      page: "Page", 
      total: "Total", 
      records: "Records", 
      repeatitems: false, 
      userdata: "UserData", 
      id: "StationId" 
     }, 
     loadui: "block", 
     mtype: 'GET', 
     rowNum: 10, 
     rowList: [10, 20, 30], 
     viewrecords: true, 
     colNames: ['Station ID', 'Station Name', 'Timestamp', 'Max Temp', 
        'Min Temp', 'Precipitation', 'Snowfall', 'SnowDepth'], 
     colModel: [ 
      { name: 'StationId', index: 'StationId' }, 
      { name: 'StationName', index: 'StationName' }, 
      { name: 'Timestamp', index: 'Timestamp', align: 'right' }, 
      { name: 'MaxTemperature', index:'MaxTemperature',align:'right'}, 
      { name: 'MinTemperature', index:'MinTemperature',align:'right'}, 
      { name: 'Precipitation', index: 'Precipitation', align:'right'}, 
      { name: 'Snowfall', index: 'Snowfall', align: 'right' }, 
      { name: 'SnowDepth', index: 'SnowDepth', align: 'right' }, 
     ], 
     pager: '#pager', 
     sortname: 'StationId', 
     sortorder: 'asc', 
     caption: 'Weather Records', 
     loadComplete: function() { 
      // if the page index is not set (e.g. page index = 0), 
      // force the page index to first page 
      var pageIndex = $('#list').jqGrid('getGridParam', 'page'); 
      if (pageIndex == 0) pageIndex = 1; 

      $('#waitIndicator').show(); 
      $.ajax({ 
       url: 'WeatherDataService.svc/GetWeatherData', 
       type: "GET", 
       data: ({ page: pageIndex, rows: 10, 
         sidx: 'StationId', sord: 'asc' }), 
       dataType: "json", 
       success: function (response) { 
        $('#resultDiv').html(response); 
        $('#waitIndicator').hide(); 
       }, 
       error: function (xmlHttpRequest, textStatus, errorThrown) { 
        $('#resultDiv').html('textStatus: ' + textStatus + 
             ', errorThrown: ' + errorThrown); 
       } 
      }); 
     } 
    }); 
}); 

Estos son los datos JSON desde el servicio web:

{ 
    "Total": 14975, 
    "Page": 1, 
    "Records": 149746, 
    "Rows": [ 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(725871600000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(725958000000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726044400000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726130800000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726217200000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726303600000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726390000000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726476400000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726562800000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     }, 
     { 
      "StationId": 50130, 
      "StationName": "ALAMOSA WSO AP", 
      "Timestamp": "\/Date(726649200000)\/", 
      "MaxTemperature": null, 
      "MinTemperature": null, 
      "Precipitation": null, 
      "Snowfall": null, 
      "SnowDepth": null 
     } 
    ], 
    "UserData": null 
} 

Para la mayoría de las columnas de los valores nulos serán resultado es celdas vacías. Pero espero ver al menos los StationID y StationNames. Gracias por echar un vistazo.

Respuesta

7

En primer lugar, si el servidor envía de vuelta los datos que ha publicado, el jqGrid mostrará los resultados (consulte http://www.ok-soft-gmbh.com/jqGrid/jsonfromsvc.htm). De la causa jqGrid voluntad no funciona muy bien, porque se utiliza como StationId el id, pero todas las filas de sus datos JSON tiene el mismo valor como el id. Entonces, por ejemplo, si selecciona una fila, se seleccionarán todas las filas.

El DateTime no es un tipo JSON estándar y no está soportado actualmente por jqGrid (ver this answer y this feature request). Para solucionar el problema, debe hacer al menos small changes tanto en datos como en jqGrid.

Los datos JSON actual tiene una gran cantidad de datos con valor nulo. Para reducir el tamaño del envío de datos vacíos desde el servidor, considere usar el atributo EmitDefaultValue.

Por otra parte me parece extraño, que no utilice parámetros como

ajaxGridOptions: { contentType: "application/json" }, 
serializeRowData: function (data) {return JSON.stringify(data);} 

(ver another old answer). Probablemente su WFC no reciba actualmente ningún parámetro de entrada como int page, int rows, string sidx, string sord y así sucesivamente). Si publica al menos prototipo de su método de servidor al que llama.

ACTUALIZADO: Cómo prometí antes de crear una pequeña aplicación WCF y una página HTML que llama al servicio WCF.

los datos actuales tiene ningún id. El campo StationId no es una clave porque es el mismo en diferentes filas de datos. Si incluye la identificación en sus datos, puede incluir en la definición de la columna la opción key:true y jqGrid usará los datos como ID. Como el ejemplo se usará solo para mostrar los datos sin edición de datos, incluí sin id en los datos enviados desde el servidor. En el caso jqGrid use un contador entero que comience con 1 como ID de fila. Si decide incluir funciones de edición en la grilla, deberá incluir como id en los datos.

Ahora vamos al código.Como escribió que usa Visual Studio 2010 y no responde nada sobre la versión de .NET, creé una aplicación en .NET 4.0. El web.config:

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
     <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 

    <system.serviceModel> 
     <standardEndpoints> 
      <webHttpEndpoint> 
       <standardEndpoint helpEnabled="true" 
            automaticFormatSelectionEnabled="true"/> 
      </webHttpEndpoint> 
     </standardEndpoints> 
     <behaviors> 
      <serviceBehaviors> 
       <behavior name=""> 
        <serviceMetadata httpGetEnabled="true" /> 
        <serviceDebug includeExceptionDetailInFaults="false" /> 
       </behavior> 
      </serviceBehaviors> 
     </behaviors> 
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
</configuration> 

File WeatherDataService.svc:

<%@ ServiceHost Factory="System.ServiceModel.Activation.WebServiceHostFactory" 
       Service="WfcToJqGrid.WeatherDataService" %> 

File IWeatherDataService.cs:

using System; 
using System.Collections.Generic; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 

namespace WfcToJqGrid { 
    [ServiceContract] 
    public interface IWeatherDataService { 
     [OperationContract, 
     WebGet (RequestFormat = WebMessageFormat.Json, 
       ResponseFormat = WebMessageFormat.Json, 
       UriTemplate = "GetWeatherData?page={page}&rows={rows}" + 
           "&sidx={sortIndex}&sord={sortDirection}")] 
     WeatherDataForJqGrid GetDataForjqGrid (int page, int rows, 
               string sortIndex, 
               SortDirection sortDirection); 
    } 

    [DataContract] 
    public enum SortDirection { 
     [EnumMember (Value = "asc")] 
     Asc, 
     [EnumMember (Value = "desc")] 
     Desc 
    } 

    // jsonReader: { repeatitems: false } 
    [DataContract] 
    public class WeatherDataForJqGrid { 
     [DataMember (Order=0, Name = "total")] 
     public int Total { get; set; }   // total number of pages 
     [DataMember (Order = 1, Name = "page")] 
     public int Page { get; set; }   // current zero based page number 
     [DataMember (Order = 2, Name = "records")] 
     public int Records { get; set; }  // total number of records 
     [DataMember (Order = 3, Name = "rows")] 
     public IEnumerable<WeatherData> Rows { get; set; } 
    } 

    [DataContract] 
    public class WeatherData { 
     [DataMember (Order=0)] 
     public int StationId { get; set; } 
     [DataMember (Order = 1)] 
     public string StationName { get; set; } 
     [DataMember (Order = 2)] 
     public DateTime Timestamp { get; set; } 
     [DataMember (Order = 3, EmitDefaultValue = false)] 
     public string MaxTemperature { get; set; } 
     [DataMember (Order = 4, EmitDefaultValue = false)] 
     public string MinTemperature { get; set; } 
     [DataMember (Order = 5, EmitDefaultValue = false)] 
     public string Precipitation { get; set; } 
     [DataMember (Order = 6, EmitDefaultValue = false)] 
     public string Snowfall { get; set; } 
     [DataMember (Order = 7, EmitDefaultValue = false)] 
     public string SnowDepth { get; set; } 
    } 
} 

File WeatherDataService.svc.sc:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.ServiceModel.Web; 
using System.Net; 

namespace WfcToJqGrid { 
    public class WeatherDataService : IWeatherDataService { 
     // we use very simple database model to simulate a real data 
     private static IQueryable<WeatherData> _repository = new List<WeatherData>{ 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,1,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,2,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,3,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,4,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,5,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,6,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,7,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,8,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
           Timestamp = new DateTime(1993,1,9,8,0,0)}, 
      new WeatherData { StationId = 50130, StationName = "ALAMOSA WSO AP", 
          Timestamp = new DateTime(1993,1,10,8,0,0)} 
     }.AsQueryable(); 

     public WeatherDataForJqGrid GetDataForjqGrid (int page, int rows, 
                 string sortIndex, 
                 SortDirection sortDirection){ 
      int totalRecords = _repository.Count(); 

      // sorting of data 
      IQueryable<WeatherData> orderdData = _repository; 
      System.Reflection.PropertyInfo propertyInfo = 
       typeof(WeatherData).GetProperty (sortIndex); 
      if (propertyInfo != null) { 
       orderdData = sortDirection == SortDirection.Desc ? 
        (from x in _repository 
        orderby propertyInfo.GetValue (x, null) descending 
        select x) : 
        (from x in _repository 
        orderby propertyInfo.GetValue (x, null) 
        select x); 
      } 

      // paging of the results 
      IEnumerable<WeatherData> pagedData = orderdData 
       .Skip ((page > 0? page - 1: 0) * rows) 
       .Take (rows); 

      // force revalidate data on the server on every request 
      if (WebOperationContext.Current != null) 
       WebOperationContext.Current.OutgoingResponse.Headers.Set (
        HttpResponseHeader.CacheControl, "max-age=0"); 

      return new WeatherDataForJqGrid { 
       Page = page, 
       Records = totalRecords, 
       Total = (totalRecords + rows - 1)/rows, 
       Rows = pagedData 
      }; 
     } 
    } 
} 

(r ead más sobre el almacenamiento en caché "jqGrid data stored in browser cache?") y default.htm:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Demonstration how use jqGrid to call WFC service</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/redmond/jquery-ui.css" /> 
    <link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/css/ui.jqgrid.css" /> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/js/i18n/grid.locale-en.js"></script> 
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-3.8/js/jquery.jqGrid.min.js"></script> 
    <script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/json2.js"></script> 
    <script type="text/javascript"> 
    //<![CDATA[ 
     jQuery(document).ready(function() { 
      $("#list").jqGrid({ 
       datatype: 'json', 
       url: 'WeatherDataService.svc/GetWeatherData', 
       jsonReader: { repeatitems: false }, 
       loadui: "block", 
       mtype: 'GET', 
       rowNum: 5, 
       rowList: [5, 10, 20, 30], 
       viewrecords: true, 
       colNames: ['Station ID', 'Station Name', 'Timestamp', 'Max Temp', 
          'Min Temp', 'Precipitation', 'Snowfall', 'SnowDepth'], 
       colModel: [ 
        { name: 'StationId', index: 'StationId', width: 100 }, 
        { name: 'StationName', index: 'StationName', width: 150 }, 
        { name: 'Timestamp', index: 'Timestamp', align: 'right', width: 250, 
         formatter: function (cellvalue, options, rowObject) { 
          // possible characters like "+0100" at the end of string will be ignored 
          return new Date(parseInt(cellvalue.substr(6, cellvalue.length - 8), 10)); 
         } 
        }, 
        { name: 'MaxTemperature', index: 'MaxTemperature', align: 'right', width: 100 }, 
        { name: 'MinTemperature', index: 'MinTemperature', align: 'right', width: 100 }, 
        { name: 'Precipitation', index: 'Precipitation', align: 'right', width: 100 }, 
        { name: 'Snowfall', index: 'Snowfall', align: 'right', width: 100 }, 
        { name: 'SnowDepth', index: 'SnowDepth', align: 'right', width: 100 }, 
       ], 
       pager: '#pager', 
       sortname: 'Timestamp', 
       sortorder: 'asc', 
       height: "100%", 
       width: "100%", 
       prmNames: { nd: null, search: null }, // we switch of data caching on the server 
                 // and not use _search parameter 
       caption: 'Weather Records' 
      }); 
     }); 
    //]]> 
    </script> 
</head> 

<body> 

<table id="list"><tr><td/></tr></table> 
<div id="pager"></div> 

</body> 
</html> 

Puede descargar el código completo here.

+0

Gracias por su respuesta, Oleg. Lamentablemente, todavía no puedo cargar la red después de implementar sus sugerencias. Cambié la información de la fecha al formato ISO y agregué "formateador: 'fecha'" a las opciones de jqGrid. También agregué las propiedades ajaxGridOptions y serializeRowData. Cuando almaceno los datos JSON en un archivo y cambio la propiedad url para que apunte al archivo, la grilla se carga. Esto me hace preguntar si el problema es con la llamada ajax y el servicio web. La firma del método se muestra en el siguiente comentario. –

+0

[WebGet (ResponseFormat = WebMessageFormat.Json, bodystyle = WebMessageBodyStyle.Bare)] \t [OperationContract] cadena pública GetWeatherData (página int, int filas, SIDX cadena, Sord cadena) { // Código para obtener los datos JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); cadena jsonOutput = jsSerializer.Serialize (DataOutput); return jsonOutput; \t}} –

+0

¿Qué versión de .NET utiliza? ¿Usas Visual Studio 2008 o 2010? Si responde las preguntas, podría publicar un ejemplo de código pequeño correspondiente. – Oleg

Cuestiones relacionadas