Domanda

ok sono tornato.Ho semplificato totalmente il mio problema in soli tre semplici campi e sono ancora bloccato sulla stessa riga utilizzando il metodo addJSONData.Sono rimasto bloccato su questo per giorni e non importa come rielaboro la chiamata Ajax, la stringa JSON, blah blah blah... NON riesco a farlo funzionare!Non riesco nemmeno a farlo funzionare come funzione quando aggiungo manualmente una riga di dati.Qualcuno può PER FAVORE pubblicare un esempio funzionante di jqGrid che funzioni con ASP.NET e JSON?Potresti includere 2-3 campi (preferibilmente stringa, numero intero e data?) Sarei felice di vedere un esempio funzionante di jqGrid e solo l'aggiunta manuale di un oggetto JSON utilizzando il metodo addJSONData.Grazie mille!!Se mai riuscissi a farlo funzionare, pubblicherò un esempio di codice completo per tutti gli altri post di aiuto da ASP.NET, anche gli utenti JSON si sono bloccati su questo.Ancora.GRAZIE!!

tbl.addJSONData(objGridData);//sbaglia:tbl.addJSONData non è una funzione!!

Ecco cosa mostra Firebug quando ricevo questo messaggio:

• oggetto objGridData totale=1 pagina=1 record=5 righe=[5]
○ Pagina "1"
Registra "5"
Totale "1"
Righe [ID oggetto=1 ID partner=BCN, ID oggetto=2 ID partner=BCN, ID oggetto=3 ID partner=BCN, altri 2...0=Oggetto 1=Oggetto 2=Oggetto 3=Oggetto 4=Oggetto]
(indice) 0
(prop) id (valore) 1 (prop) partnerid (valore) "bcn" (prop) datetimeinserted (value) thu 29 maggio 2008 12:08:45 GMT-0700 (tempo diurno del Pacifico)
* Ci sono altre tre righe

Ecco il valore della variabile tbl (valore) '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>

Ecco la funzione 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")};  
È stato utile?

Soluzione

Ecco un semplice esempio ...

Sarà necessario https://github.com/douglascrockford/JSON -js / blob / master / json2.js per questo al lavoro ...

, naturalmente, i file jQuery usuali e.

Incolla ad un webservice

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

Incolla questo alla tua pagina 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>

Altri suggerimenti

Di solito quando si ottiene il 'non bla una funzione' errore jqGrid è perché il modulo corretto non è stato caricato. La funzione addJSONData è definita nel file grid.base.js. Si può controllare la funzione jqGridInclude () nel file jquery.jqGrid.js e assicurarsi che grid.base.js è stata inclusa come parte della inizializzazione della variabile di moduli?

Hai verificato la variabile TBL è sempre riferimento alla propria istanza jqGrid?

Prova ad aggiungere un id al vostro elemento di tabella e ottenere il riferimento al jqGrid come:

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

e vedo una cosa sbagliata qui:

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

se si sta effettivamente chiedendo perché hai trovato questo errore, è perché TBL non ha questa funzione.

Edit: ho ottenuto curioso e controllato se jqGrid aggiunto questi metodi per l'oggetto di riferimento DOM. e lo hanno fatto. (Ho controllato usando Firebug qui: http://trirand.com/jqgrid/jqgrid.html ).

Una cosa che può accadere è che si dispone di più tavole di classe 'scorrere' e la vostra jquery sta tornando quella sbagliata.

Dato che abbiamo ricevuto molte domande per ASP.NET WebForms e jqGrid, abbiamo deciso di seguire la strada del "componente" e implementare qualcosa che sia molto simile ad asp:GridView.In questo modo, puoi controllare jqGrid utilizzando il familiare ciclo di vita della pagina ASP.NET, eventi, origini dati, ecc.

Puoi vederne una beta online qui: attualmente sono disponibili più di 30 campioni:

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

Molto probabilmente diventerà anche un prodotto commerciale (saranno disponibili licenze open source) se c'è interesse in questo.Nel frattempo, puoi utilizzare Reflector per controllare le fonti come riferimento (finché non troveremo un modo per rendere la fonte disponibile online).Stiamo utilizzando SVN per ASP.NET anziché gitHub per js Core, quindi abbiamo del lavoro in quella direzione.

Speriamo che questo aiuti la comunità.

Rumen Stankov Trirand

Questa è una domanda molto vecchio, però, ho avuto lo stesso problema solo di recente. Ho postato come ho raggiunto questo su un nuovo blog che sto cercando di iniziare.

Ci possono essere modi più puliti di fare questo, ma questo ha funzionato per me. Finora sono stato in grado di scalare fino da questo esempio abbastanza facilmente. Il mio prossimo ostacolo è sempre la loadonce al lavoro.

È possibile trovare il mio esempio qui:

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

WebForm sta morendo fuori, quindi abbiamo bisogno di concentrarsi sulle più recenti tecnologie come asp.net MVC. Ho trovato una nuova integrazione asp.net jqGrid qui http://www.techdoubts.net/2017/05/full-integration-dynamic-jqgrid-asp-net-mvc.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top