Cannot read property '__count' of undefined Kendo UI Grid MVC Web API Odata

When trying to connect a Kendo UI Grid to an MVC Web API datasource I was getting the following error: 

Cannot read property ‘__count’ of undefined

The problem is the format of the json being returned contains a value with the total number of records that can be used for paging. Solution is to add the following lines to your schema for the data source:

data: function (data) { return data; }, 
total: function (data) { return data['odata.count']; }, 

Here is my compete code:

$(".tripSnapshotGrid").kendoGrid({
    dataSource: {
        type: "odata",
        transport: {
            read: {
                url: toll.settings.app_url + "api/TripSnapshots/Get",
                dataType: "json"
            }
        },
        schema: {
            data: function (data) {
                return data;
            },
            total: function (data) {
                return data['odata.count'];
            },
            model: {
                fields: {
                    ID: { type: "number" },
                    TripName: { type: "string" },
                    TripState: { type: "string" }
                }
            }
        },
        pageSize: 20,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true
    },
    filterable: true,
    sortable: true,
    pageable: true,
    columns: [{
        field: "TripState",
        filterable: false,
        width: 90
    }, {
        field: "TripName",
        filterable: false
    }

    ]
});
comments powered by Disqus