How to Bind jqGrid with asmx webservice C#

2019-04-12 02:37发布

问题:

Please i need some help in how to bind jqGrid with asmx webservice C# , i found some topics in how to convert asmx webservice to JSON but it's not clear with me

Regards

回答1:

First of all you should define WebMethod which will provide the data for the jqGrid. If you plan to implement server side sorting and paging the webmethod should have at least the following parameters

public JqGridData TestMethod (int page, int rows, string sidx, string sord)

where JqGridData class will be defined for example like

public class TableRow {
    public int id { get; set; }
    public List<string> cell { get; set; }
}
public class JqGridData {
    public int total { get; set; }
    public int page { get; set; }
    public int records { get; set; }
    public List<TableRow> rows { get; set; }
}

There are other different options how one can fill the grid, but it's first important to understand at least one way.

It's important, that to return JSON data from the web method you don't need to convert the returned data manually to JSON. You need just return the object with the data and the ASMX web service will serialize the object itself to XML or JSON based on the headers of the HTTP request.

It the request to the server will have application/json; charset=utf-8 or application/json in the Content-Type part of the HTTP header, the returned data will be JSON and will be

{
    "d": {
        "page": 1,
        "total": 4,
        "records": 4,
        "rows": [
            ...
        ]
    }
}

On the client side you should use

$("#list").jqGrid({
    url: 'MyTestWS.asmx/TestMethod',
    datatype: 'json',
    mtype: 'POST',
    ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
    serializeGridData: function (postData) {
        return JSON.stringify(postData);
    },
    jsonReader: {
        root: "d.rows",
        page: "d.page",
        total: "d.total",
        records: "d.records"
    }
    gridview: true,
    ...
}

See here for a code example.

UPDATED: Here and here you can download Visual Studio demo projects. See the answer for more links to other demo projects.