Question

ok, je suis de retour. Je suis totalement simplifié mon problème à seulement trois champs simples et je suis toujours bloqué sur la même ligne en utilisant la méthode addJSONData. Je suis coincé sur ce pendant des jours et peu importe comment je retravaille l'appel ajax, la chaîne JSON, bla bla bla ... Je ne peux pas obtenir ce travail! Je ne peux même pas faire fonctionner en fonction lors de l'ajout d'une ligne de données manuellement. Quelqu'un peut-il S'IL VOUS PLAÎT poster un extrait de travail de jqGrid qui fonctionne avec ASP.NET et JSON? Pourriez-vous s'il vous plaît inclure 2-3 champs (string, integer et date de préférence?) Je serais heureux de voir un échantillon de travail de jqGrid et juste l'ajout manuel d'un objet JSON en utilisant la méthode addJSONData. Merci beaucoup!! Si jamais je reçois ce travail, je vais poster un exemple de code complet pour tous les autres l'affichage à l'aide d'ASP.NET, les utilisateurs JSON coincés sur cela aussi. Encore. MERCI!!

tbl.addJSONData (objGridData); // err: tbl.addJSONData est pas une fonction !!

Voici ce que Firebug montre quand je reçois ce message:

• objGridData objet total = 1 page = 1 = 5 enregistrements rangs = [5]
    ○ la page "1"
    Dossiers
"5"     Total des
"1"     Lignes [ID de l'objet = 1 PartnerID = BCN, Object ID = 2 PartnerID = BCN, Object ID = 3 = PartnerID BCN, 2 0 plus ... = Objet 1 = 2 = Object Objet 3 = 4 = Object Objet]
            (Index) 0
                      (Prop) ID (valeur) 1               (Prop) PartnerID (valeur) "BCN"                   (Prop) DateTimeInserted (valeur) 29 Jeu mai 2008 12:08:45 GMT-0700 (heure avancée du Pacifique)
        * Il y a plus de trois lignes

Voici la valeur de la TBL variable (valeur) '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>

Voici la fonction complète:

 $('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")};  
Était-ce utile?

La solution

Voici un exemple simple ...

Vous aurez besoin https://github.com/douglascrockford/JSON -js / blob / maître / json2.js pour que cela fonctionne ...

et bien sûr les fichiers jquery habituels.

Coller à 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;
    }
}

Coller ceci à votre page 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>

Autres conseils

En général, quand vous obtenez le « bla pas une fonction » erreur avec jqGrid c'est parce que le module correct n'a pas été chargé. La fonction addJSONData est définie dans le fichier grid.base.js. Pouvez-vous vérifier votre fonction jqGridInclude () dans le fichier jquery.jqGrid.js et assurez-vous que grid.base.js est en cours inclus dans le cadre de l'initialisation de votre variable de modules?

Avez-vous vérifié la variable TBL devient référence à votre instance jqGrid?

Essayez d'ajouter un identifiant à votre élément de table et obtenir la référence à la jqGrid comme:

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

Eh bien, je vois mal une chose ici:

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

si vous vous demandez bien pourquoi vous obtenez cette erreur, il est parce que TBL n'a pas cette fonction.

Edit: je suis curieux, et vérifié si jqGrid ajouté ces méthodes à l'objet de référence DOM. et ils l'ont fait. (I vérifié à l'aide Firebug ici: http://trirand.com/jqgrid/jqgrid.html ).

Une chose qui peut se passer ici est que vous avez plusieurs tables de classe « scroll » et votre jquery renvoie le mauvais.

Depuis que nous avons eu beaucoup de questions pour ASP.NET WebForms et jqGrid, nous avons décidé d'aller dans le sens de « composants » et mettre en œuvre quelque chose qui est très similaire à asp: GridView. De cette façon, vous pouvez contrôler jqGrid en utilisant le cycle de vie de page ASP.NET familier, événements, sources de données, etc.

Vous pouvez voir une version bêta de cette ligne ici - plus de 30 échantillons disponibles actuellement:

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

Il sera très probablement se transformer en produit commercial et (licences open source seront disponibles) s'il y a dans cet intérêt. Pendant ce temps, vous pouvez utiliser réflecteur pour vérifier les sources de référence (jusqu'à ce que nous trouver un moyen d'avoir la source disponible en ligne). Nous utilisons SVN pour ASP.NET, par opposition à GitHub pour le Core js, nous avons donc un travail dans ce sens.

Nous espérons que cela aide la communauté.

Rumen Stankov Trirand

Ceci est une question très ancienne, cependant, je faisais la même question tout récemment. J'ai posté comment j'ai réalisé cela sur un nouveau blog je tente de commencer.

Il peut y avoir des moyens plus propres de le faire, mais cela a fonctionné pour moi. Jusqu'à présent, je suis en mesure d'évoluer à partir de cet exemple assez facilement. Mon prochain obstacle devient le loadonce à travailler.

Vous pouvez trouver mon exemple ici:

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

WebForm est en train de mourir, donc nous devons nous concentrer sur les dernières technologies comme asp.net MVC. J'ai trouvé une nouvelle intégration asp.net de jqGrid ici http://www.techdoubts.net/2017/05/full-integration-dynamic-jqgrid-asp-net-mvc.html

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top