Search code examples
c#jsonjqgridmvcjqgrid

Jqgrid local data formated using Jsonconvert not working


I am trying to populate jqgrid with data stored in a hidden field. I have successfully tried the method of populating the grid from serverdata (data type= json). But here I need it this way. Here is what I did:

Controller:

      DataTable myTable= MyData.getAllData();

      string s = JsonConvert.SerializeObject(myTable);

       model.GridData = s;

       return this.View(model);

View:

var mydata = $('#GridData').val();

When I use alert(mydata ) here, I can see

[{ "id": 1, "ToCurrencyID": 2, "currency": "United Arab Emirates", "country": "United Arab Emirates dirham", "shortName": "AED", "ExchRate": 20.000}]

And here is the jqgrid code:

    jQuery(document).ready(function () {
        jQuery("#list").jqGrid({ data: mydata,
            datatype: "local",
            height: 150,
            width: 600,
            rowNum: 10,
            rowList: [10, 20, 30],
            colNames: ['Sl#', 'currencyId_Hidden', 'Country', 'Currency', 'Short Name', 'Exchange Rate'],
            //columns model/*
            colModel: [
                        { name: 'id', index: 'id', align: "left", sortable: false, width: '34px' },
                        { name: 'ToCurrencyID', index: 'ToCurrencyID', sortable: false, align: "left", hidden: true },
                        { name: 'currency', index: 'currency', align: "left", sortable: false, width: '366px' },
                        { name: 'country', index: 'country', align: "left", sortable: false, width: '366px' },
                        { name: 'shortName', index: 'shortName', width: '141px', sortable: false, align: "left" },
                        { name: 'ExchRate', index: 'ExchRate', width: '382px', sortable: false, align: "right" }
                  ],
            pager: "#pager",
            loadonce: true,
            viewrecords: true,
            caption: "Contacts"
        });

    });

The problem is that, grid is not getting populated.

But, when I directly use,

var mydata=[{ "id": 1, "ToCurrencyID": 2, "currency": "United Arab Emirates", "country": "United Arab Emirates dirham", "shortName": "AED", "ExchRate": 20.000}];

it, is working fine.

I think jqgrid needs a json array itself, not just a string. Any suggestions?


Solution

  • I just needed to convert the mydata(which is now a string variable) to Json. And everything works fine now.

          jQuery("#list").jqGrid({ data: $.parseJSON(mydata),
                    datatype: "local",
                    height: 150,
                    width: 600,
                    rowNum: 10,
                    rowList: [10, 20, 30],
                   .. 
                   ..
                  });