Pregunta

Bien, estoy de vuelta.Simplifiqué totalmente mi problema a solo tres campos simples y todavía estoy atascado en la misma línea usando el método addJSONData.He estado atascado en esto durante días y no importa cómo reelabore la llamada ajax, la cadena json, bla, bla, bla... ¡NO puedo hacer que esto funcione!Ni siquiera puedo hacer que funcione como una función cuando agrego una fila de datos manualmente.¿Alguien puede POR FAVOR publicar una muestra funcional de jqGrid que funcione con ASP.NET y JSON?¿Podría incluir 2 o 3 campos (cadena, número entero y fecha preferiblemente?) Me encantaría ver una muestra funcional de jqGrid y solo la adición manual de un objeto JSON utilizando el método addJSONData.¡¡Muchas gracias!!Si alguna vez logro que esto funcione, publicaré un ejemplo de código completo para todas las demás publicaciones para obtener ayuda de ASP.NET, los usuarios de JSON también se quedaron atrapados en esto.De nuevo.¡¡GRACIAS!!

tbl.addJSONData(objGridData);//errar:¡tbl.addJSONData no es una función!

Esto es lo que muestra Firebug cuando recibo este mensaje:

• objGridData Objeto total=1 página=1 registros=5 filas=[5]
○ Página "1"
Registros "5"
Total "1"
Filas [ID de objeto=1 ID de socio=BCN, ID de objeto=2 ID de socio=BCN, ID de objeto=3 ID de socio=BCN, 2 más...0=Objeto 1=Objeto 2=Objeto 3=Objeto 4=Objeto]
(índice) 0
(prop) ID (valor) 1 (prop) PartnerID (valor) "BCN" (prop) DateTimeInserted (valor) Thu May 29, 2008 12:08:45 GMT-0700 (Hora de verano del Pacífico)
*Hay tres filas más

Aquí está el valor de la variable tbl (valor) 'Table.scroll'

<TABLE cellspacing="0" cellpadding="0" border="0" style="width: 245px;" class="scroll grid_htable"><THEAD><TR><TH class="grid_sort grid_resize" style="width: 55px;"><SPAN> </SPAN><DIV id="jqgh_ID" style="cursor: pointer;">ID <IMG src="http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif"/></DIV></TH><TH class="grid_resize" style="width: 90px;"><SPAN> </SPAN><DIV id="jqgh_PartnerID" style="cursor: pointer;">PartnerID </DIV></TH><TH class="grid_resize" style="width: 100px;"><SPAN> </SPAN><DIV id="jqgh_DateTimeInserted" style="cursor: pointer;">DateTimeInserted </DIV></TH></TR></THEAD></TABLE>

Aquí está la función completa:

 $('table.scroll').jqGrid({  
    datatype: function(postdata) {    
        mtype: "POST",    
    $.ajax({  
        url: 'EDI.asmx/GetTestJSONString',  
        type: "POST",  
        contentType: "application/json; charset=utf-8",  
        data: "{}",  
        dataType: "text", //not json . let me try to parse  
        success: function(msg, st) {  
            if (st == "success") {                    
                 var gridData;  

                //strip of "d:" notation  
                var result = JSON.parse(msg);   
                for (var property in result) {  
                    gridData = result[property];  
                    break;  
                }  

                var objGridData = eval("(" + gridData + ")"); //creates an object with visible data and structure  
                var tbl = jQuery('table.scroll')[0];  

                alert(objGridData.rows[0].PartnerID); //displays the correct data  

                //tbl.addJSONData(objGridData); //error received: addJSONData not a function  

                //error received: addJSONData not a function (This uses eval as shown in the documentation)  
                //tbl.addJSONData(eval("(" + objGridData + ")"));   

                //the line below evaluates fine, creating an object and visible data and structure  
                //var objGridData = eval("(" + gridData + ")");  
                //BUT, the same thing will not work here  
                //tbl.addJSONData(eval("(" + gridData + ")"));  
                //FIREBUG SHOWS THIS AS THE VALUE OF gridData:  
               // "{"total":"1","page":"1","records":"5","rows":[{"ID":1,"PartnerID":"BCN","DateTimeInserted":new Date(1214412777787)},{"ID":2,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125000)},{"ID":3,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125547)},{"ID":4,"PartnerID":"EHG","DateTimeInserted":new Date(1235603192033)},{"ID":5,"PartnerID":"EMDEON","DateTimeInserted":new Date(1235603192000)}]}"         

            }  
        }  
    });  
    },  
    jsonReader: {  
        root: "rows", //arry containing actual data  
        page: "page", //current page  
        total: "total", //total pages for the query  
        records: "records", //total number of records  
        repeatitems: false,  
        id: "ID" //index of the column with the PK in it   
    },  
    colNames: [  
        'ID', 'PartnerID', 'DateTimeInserted'  
          ],    
    colModel: [    
    { name: 'ID', index: 'ID', width: 55 },    
    { name: 'PartnerID', index: 'PartnerID', width: 90 },  
    { name: 'DateTimeInserted', index: 'DateTimeInserted', width: 100}],  
    rowNum: 10,  
    rowList: [10, 20, 30],  
    imgpath: 'http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images',  
    pager: jQuery('#pager'),  
    sortname: 'ID',  
    viewrecords: true,  
    sortorder: "desc",  
   caption: "TEST Example")};  
¿Fue útil?

Solución

Este es un ejemplo sencillo ...

https://github.com/douglascrockford/JSON -js / blob / master / json2.js para que esto funcione ...

y por supuesto los archivos jquery habituales.

Pegar a un servicio web

// The lower case properties here are required to be lower case
// I cant find a way to rename them when they are serialized to JSON
// XmlElement("yournamehere") does not work for JSON :(
public class JQGrid
{
    public class Row
    {
        public int id { get; set; }
        public List<string> cell { get; set; }

        public Row()
        {
            cell = new List<string>();
        }
    }

    public int page { get; set; }
    public int total { get; set; }
    public int records { get; set; }
    public List<Row> rows { get; set; }

    public JQGrid()
    {
        rows = new List<Row>();
    }
}


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public JQGrid GetJQGrid(int page, int pageSize, string sortIndex, string sortDirection)
    {
        DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, "udsp_GetMyData",pageIndex, pageSize);

        if (ds == null || ds.Tables.Count < 1)
            throw new Exception("Unable to retrieve data.");

        JQGrid jqGrid = new JQGrid();

        int i = 1;
        foreach (DataRow dataRow in ds.Tables[0].Rows)
        {
            JQGrid.Row row = new JQGrid.Row();

            row.id = Convert.ToInt32(dataRow["MyIdColumn"]);

            row.cell.Add(dataRow["MyIdColumn"].ToString());

            row.cell.Add(dataRow["MyColumn"].ToString());


            projectGrid.rows.Add(row);
        }

        jqGrid.page = 1; // Set this when you are actually doing paging... this is just a sample
        jqGrid.records = jqGrid.rows.Count;
        jqGrid.total = jqGrid.rows.Count;  // Set this to total pages in your result...

        return jqGrid;
    }
}

Pegar esto a su página aspx

<script type="text/javascript">
function getData(pdata) {
    var params = new Object();
    params.page = pdata.page;
    params.pageSize = pdata.rows;
    params.sortIndex = pdata.sidx;
    params.sortDirection = pdata.sord;


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/CLM/CLM.asmx/GetProjectGrid2",
        data: JSON.stringify(params),
        dataType: "json",
        success: function(data, textStatus) {
            if (textStatus == "success") {
                var thegrid = $("#testGrid")[0];
                thegrid.addJSONData(data.d);
            }
        },
        error: function(data, textStatus) {
            alert('An error has occured retrieving data!');
        }
    });
}

var gridimgpath = '/clm/css/ui-lightness/images';
$(document).ready(function() {
    $("#testGrid").jqGrid({
        datatype: function(pdata) {
            getData(pdata);
        },
        colNames: ['My Id Column', 'My Column'],
        colModel: [
            { name: 'MyIdColumn', index: 'MyIdColumn', width: 150 },
            { name: 'My Column', index: 'MyColumn', width: 250 }
        ],
        rowNum: 10,
        rowList: [10, 20, 30],
        imgpath: gridimgpath,
        pager: jQuery('#pagerdt'),
        sortname: 'id',
        viewrecords: false,
        sortorder: "desc",
        caption: "Projects",
        cellEdit: false
    });
});
</script>

Otros consejos

Por lo general, cuando obtiene el 'bla no es una función' error con jqGrid es porque el módulo correcto no se ha cargado. La función addJSONData se define en el archivo grid.base.js. Se puede comprobar su función jqGridInclude () en el archivo jquery.jqGrid.js y asegúrese de que grid.base.js está siendo incluido como parte de la inicialización de la variable de módulos?

¿ha comprobado la variable TBL es cada vez referencia a la instancia jqGrid?

Trate de añadir un identificador a su elemento de la tabla y obtener la referencia a la jqGrid como:

var thegrid = jQuery("#mytableid")[0];

Bueno, yo veo una cosa mal aquí:

var tbl = jQuery('table.scroll')[0];  
 //tbl.addJSONData(objGridData); //error received: addJSONData not a function  

Si usted es de hecho preguntando por qué usted está recibiendo este error, es porque TBL no tiene esa función.

Edit: i picó la curiosidad, y se comprueba si jqGrid añadió esos métodos al objeto de referencia DOM. y lo hicieron. (He comprobado usando firebug aquí: http://trirand.com/jqgrid/jqgrid.html ).

Una cosa que puede estar ocurriendo es que tiene varias tablas de clase 'scroll' y su jQuery es devolver el equivocado.

Como recibimos muchas preguntas sobre ASP.NET WebForms y jqGrid, decidimos optar por el camino de los "componentes" e implementar algo que es muy similar a asp:GridView.De esta manera, puede controlar jqGrid utilizando el familiar ciclo de vida de la página ASP.NET, eventos, fuentes de datos, etc.

Puede ver una versión Beta de esto en línea aquí: más de 30 muestras disponibles actualmente:

http://www.trirand.net/demo.aspx

Lo más probable es que también se convierta en un producto comercial (habrá licencias de código abierto disponibles) si hay interés en ello.Mientras tanto, puede utilizar Reflector para consultar las fuentes como referencia (hasta que encontremos una manera de tener la fuente disponible en línea).Estamos usando SVN para ASP.NET en lugar de gitHub para js Core, por lo que tenemos algo de trabajo en esa dirección.

Esperamos que esto ayude a la comunidad.

Rumen Stankov Trirand

Esta es una pregunta muy antigua, sin embargo, estaba teniendo el mismo problema hace poco. He publicado la forma en que he logrado esto en un nuevo blog que estoy tratando de empezar.

Puede haber formas más limpias de hacer esto, pero esta trabajado para mí. Hasta ahora he sido capaz de escalar a partir de este ejemplo con bastante facilidad. Mi siguiente obstáculo es conseguir que el loadonce funcione.

Puede encontrar mi ejemplo aquí:

http://programming.webdad3.com/?p=3

WebForm está muriendo, por lo que necesitamos para centrarse en las últimas tecnologías, como asp.net MVC. He encontrado una nueva integración asp.net jqGrid aquí http://www.techdoubts.net/2017/05/full-integration-dynamic-jqgrid-asp-net-mvc.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top