views:

7983

answers:

6

Dear community !

I am a bit lost. I' ve tried to implement a solution based on JqGrid and tried to use function as datatype. I've setted all by the book i guess, i get WS invoked and get JASON back, I got succes on clientside in ajaf call and i "bind" jqGrid using addJSONData but grid remains empty. I do not have any glue now... other "local" samples on same pages works without a problem (jsonstring ...)

My WS method looks like :

 
[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetGridData()  
         {  
             // Load a list 
             InitSessionVariables();
             SA.DB.DenarnaEnota.DenarnaEnotaDB db = new SAOP.SA.DB.DenarnaEnota.DenarnaEnotaDB();
             DataSet ds = db.GetLookupForDenarnaEnota(SAOP.FW.DB.RecordStatus.All);

             // Turn into HTML friendly format  
             GetGridData summaryList = new GetGridData();

             summaryList.page = "1";
             summaryList.total = "10";
             summaryList.records = "160";
             int i = 0;
             foreach (DataRow dr in ds.Tables[0].Rows)  
             {
                 GridRows row = new GridRows();
                 row.id = dr["DenarnaEnotaID"].ToString();
                 row.cell = "[" + "\"" + dr["DenarnaEnotaID"].ToString() + "\""
                                       + "," + "\"" + dr["Kratica"].ToString() + "\""
                                       + "," + "\"" + dr["Naziv"].ToString() + "\""
                                       + "," + "\"" + dr["Sifra"].ToString() + "\""

                          + "]";
                 summaryList.rows.Add(row);
             }  
             return JsonConvert.SerializeObject(summaryList);

         }

my ASCX code is this:


jQuery(document).ready(function(){
jQuery("#list").jqGrid({
                        datatype : function (postdata) { jQuery.ajax({ url:'../../AjaxWS/TemeljnicaEdit.asmx/GetGridData', 
                                                                       data:'{}', 
                                                                       dataType:'json', 
                                                                       type: 'POST',
                                                                       contentType: "application/json; charset=utf-8",
                                                                       complete: function(jsondata,stat){ 
                                                                                                         if(stat=="success") 
                                                                                                         { 
                                                                                                              var clearJson = jsondata.responseText;

                                                                                                              var thegrid = jQuery("#list")[0]; 
                                                                                                              var myjsongrid = eval('('+clearJson+')');
                                                                                                              alfs
                                                                                                              thegrid.addJSONData(myjsongrid.replace(/\\/g,''));
                                                                                                         } 
                                                                                                        } 
                                                                     }
                                                                    ); 
                                                       }, 
                        colNames:['DenarnaEnotaID','Kratica', 'Sifra', 'Naziv'], 
                        colModel:[ 
                                   {name:'DenarnaEnotaID',index:'DenarnaEnotaID', width:100}, 
                                   {name:'Kratica',index:'Kratica', width:100}, 
                                   {name:'Sifra',index:'Sifra', width:100}, 
                                   {name:'Naziv',index:'Naziv', width:100}], 

                        rowNum:15, 
                        rowList:[15,30,100], 
                        pager: jQuery('#pager'), 
                        sortname: 'id', 
                      //  loadtext:"Nalagam zapise...",
                       // viewrecords: true, 
                        sortorder: "desc", 
                       // caption:"Vrstice", 
                       // width:"800",
                        imgpath: "../Scripts/JGrid/themes/basic/images"}); 

               });

from WS i GET JSON like this:


{”page”:”1″,”total”:”10″,”records”:”160″,”rows”:[{"id":"18","cell":"["18","BAM","Konvertibilna marka","977"]“},{”id”:”19″,”cell”:”["19","RSD","Srbski dinar","941"]“},{”id”:”20″,”cell”:”["20","AFN","Afgani","971"]“},{”id”:”21″,”cell”:”["21","ALL","Lek","008"]“},{”id”:”22″,”cell”:”["22","DZD","Alžirski dinar","012"]“},{”id”:”23″,”cell”:”["23","AOA","Kvanza","973"]“},{”id”:”24″,”cell”:”["24","XCD","Vzhodnokaribski dolar","951"]“},{”id”:”25″,”cell”:”

………………

["13","PLN","Poljski zlot","985"]“},{”id”:”14″,”cell”:”["14","SEK","Švedska krona","752"]“},{”id”:”15″,”cell”:”["15","SKK","Slovaška krona","703"]“},{”id”:”16″,”cell”:”["16","USD","Ameriški dolar","840"]“},{”id”:”17″,”cell”:”["17","XXX","Nobena valuta","000"]“},{”id”:”1″,”cell”:”["1","SIT","Slovenski tolar","705"]“}]}

i have registered this js :


   clientSideScripts.RegisterClientScriptFile("prototype.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/prototype-1.6.0.2.js"));

            clientSideScripts.RegisterClientScriptFile("jquery.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.js"));
            clientSideScripts.RegisterClientScriptFile("jquery.jqGrid.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/jquery.jqGrid.js"));
            clientSideScripts.RegisterClientScriptFile("jqModal.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqModal.js"));
            clientSideScripts.RegisterClientScriptFile("jqDnR.js", CommonFunctions.FixupUrlWithoutSessionID("~/WebUI/Scripts/JGrid/js/jqDnR.js"));

Basical i think it must be something stupid ...but i can figure it out now...

Help wanted.

+6  A: 

I've been trying to solve the same problem for the last couple of hours. I've now given up on getting AddJSONData working - my web service method is returning an array so it looks like using addRowData will work.

function ReceivedClientData(data) {
        var thegrid = $("#list4");
        for (var i = 0; i < data.length; i++) {
            thegrid.addRowData(i+1, data[i]);
        }
    }
thank you, this is solution :)please someone put Tom's answer as answer :)cheers
Marko
If you aren't paging, you could embed the rows into an object tag...{ 'page':1, 'total':1, 'records':rows.length, 'records':rows } and use that with addJSONData.
Tracker1
this is solution with little modifications depending on what you get from webservice...for me it is: success: function(jsondata, stat) { var thegrid = $("#list"); var evaluated = JSON.parse(jsondata.d); for (var i = 0; i < evaluated.length; i++) { thegrid.addRowData(i + 1, evaluated[i]); } }
Marko
A: 

Actually, the key seems to be the parameters on addJSONData which don't appear in the docs:

function ReceivedClientData(data) {
        var thegrid = $("#rowed2");
        thegrid[0].addJSONData(data,thegrid.bDiv,9)            
    }

The web method that goes with that is :

    [WebMethod(EnableSession = true)]
    public object GetTestClients(int pagenum, int rows)
    {
        var lst = Session["lst"] as List<Entities.Client>;
        if (lst == null)
        {
            lst = new List<Entities.Client>();
            for (int i = 1; i <= 5; i++)
            {
                lst.Add(new TF.WebApps.Entities.Client()
                {
                    ClientID = "Client" + i,
                    Firstname = "first" + i,
                    Lastname = "last" + i
                });
            }
            Session["lst"] = lst;
        }
        var v = from c in lst
                select new
                {
                    id = c.ClientID,
                    cell = new object[] 
                    {
                        c.ClientID,
                        c.Firstname,
                        c.Lastname
                    }
                };

        var result = new
        {
            total = v.Count() / rows,
            page = pagenum,
            records = rows,
            rows = v.Skip((pagenum-1)*rows).Take(rows).ToArray()
        };


        return result;
    }
A: 

The setup of the jqGrid looks fine.

Are you certain that what you get back in the jsondata.responseText is what you describe?

The webservice that I write in .NET returns JSON formatted like this: {"d": "{”page”:”1″,”total”:”10″,”records”:”160″,”rows”:[{"id":"18","cell":"["18","BAM","Konvertibilna marka","977"]“}"

In my function I had to do this:

complete: function(data) { var stuff = JSON.parse(data.responseText); jQuery("#grid")[0].addJSONData(JSON.parse(stuff.d)); }

I had to convert the string to JSON two times before I actually got the data I needed.

If you're having great problems. I suggest debugging this piece by piece. Execute a simple statement such as this:

jQuery("#list")[0].addJSONData(JSON.parse("{total: 1, page: 1, records: 1, rows : [ {id: '1', cell:['1', '2007-10-01', 'test', 'note', 'new', '200.00', '10.00', '210.00']} ] }"));

That should work at the very least. After that, just analyze the output you get from the web service and ensure that you can just get that statement to execute for 'complete'.

Lobut
I get json like the one posted because i use non .net JSON serializer.
MilosC
Right, just double-checking.Did you try attempting to just execute the function on your own, during the document.ready or during an onclick function?Just to see if it adds it on its own?
Lobut
A: 

thanks, this works for me:

mygrid[0].addJSONData(result, mygrid.bDiv, 0);

or try this:

mygrid[0].addJSONData($.toJSON(result), mygrid.bDiv, 0);

my grid datatype is jsonstring

gr

Atam Panday

A: 

I'm also using a webservice to pass data to a jqGrid. I ran into the same problem and here is the code in the complete portion of the .ajax function.


complete: function(jsondata, stat) {
             if (stat == "success") {
                var thegrid = jQuery("#list2")[0];
                var jsonObject = eval('(' + jsondata.responseText + ')');
                thegrid.addJSONData(jsonObject.d);
             }
           }

The key is the .d after the responseText is evaluated into a JSON Object.

Frenchie
A: 

I know it's old, but this is probably your issue...

Make row.cell a List, then you can do...

row.cell = new List {
    dr["DenarnaEnotaID"]
    ,dr["Kratica"]
    ,dr["Naziv"]
    ,dr["Sifra"]
};

On the script side...

var myjsongrid = eval('('+clearJson+')');
...
thegrid.addJSONData(myjsongrid.replace(/\\/g,''));

myjsongrid is an Object at this point, there generally isn't a .replace method on objects. Also, you should probably use a JSON parser insted of the eval. I use a modified version of Crockford's json2.js myself but YMMV.

This should make each row how you want it, letting the serializer handling the conversion... I actually serialize my datatables to { columns:['colname',...], rows:[['row1val',...],['row2val',...],...] } and frob it client-side as I use some of the same calls to populate various grids... I have a client-side selectForJqGrid(table, keycol, [col list]) that will set it up for use direct to a jqGrid.

Tracker1