简体   繁体   中英

jqGrid - loading values from JSON

I have a jqGrid working OK using the local datatype, but I now want the values to be loaded via json but having trouble changing it.

This is my jqGrid code

jQuery("#grid").jqGrid({
        datatype: "json",
        url: "/controller/getItems?id=2",
        width: 1405,
        colNames: ['id', 'surname'],
        colModel: [
            { name: 'id', index: 'id', editable: false, hidden: false, hidedlg: true },
            { name: 'surname', index: 'surname', editable: true }
        ],
        onSelectRow: function (id, status, e) {

        ...
    },
    editurl: url,

     ...

So the method to get the JSON is sucessfully fired.

    [HttpGet]
    public ActionResult getItems(string id)
    {

        List<model> items = method.getItems(id);
        string jsonText = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(items);
        return Json(jsonText, JsonRequestBehavior.AllowGet);

    }

The column names in the JSON do match the colModel names

Example of the json being returned - what the object jsonText above contains

[{"id":434,"surname":"Woods"},
{"id":435,"surname":"Adams"}]

Is there anything I have done wrong or am missing?

Thanks

I suppose that the error in in using of System.Web.Script.Serialization.JavaScriptSerializer().Serialize . You need just return Json(items, JsonRequestBehavior.AllowGet); . Additionally you can remove the column id from the colModel . The id value will be still read and assigned as the value of id attribute of the rows ( id of <tr> elements of the grid) known as rowid. You should add loadonce: true option to the grid because you don't implemented paging of data on the server side and to add gridview: true (if you not already use it) to have better performance and autoencode: true to interpret input data as texts instead of HTML fragments.

UPDATED : In case of usage old version of jqGrid one have to include jsonReader parameter which corresponds the format of input data:

jsonReader: {
    repeatitems: false,
    root: function (obj) { return obj; }
}

One should still use loadonce: true option additionally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM