1
votes

Sometimes I like to use the HTML5/Javascript implementations of the Kendo framework because you can do some things a little easier. In this case I need to know the number of results so I can either display a kendo grid or not, however other times I need to modify the datasource based on user input on the client side. Unfortunately you can't get the number of results or modify the datasource (as far as I know) using the MVC wrappers. How can I call the controller using the Javascript implementation of the Kendo datasource?

1

1 Answers

4
votes

I was able to get this working using the following code:

Controller:

public ActionResult GetStuff(string parameter)
{
    // Get your data here ...
    var data = GetData(parameter);

    return Json(data, JsonRequestBehavior.AllowGet);

} // end

Markup/cshtml:

<div id='myGrid'></div>

<script>

    $(document).ready(function () {

        // Define the dataSource, note that the schema elements are specified
        var dataSource = new kendo.data.DataSource({
            dataType: "json",
            type: "GET",
            transport: {
                read: '@Url.Action("MethodName", "ControllerName", new {parameter = myParameter} )'         
            },            
            schema: {
                data: "Stuff",
                total: "TotalNumberofStuff",
                errors: "ErrorMessage"
            }
        });
    }

    // Call fetch on the dataSource - this gets the data - the fetch method will make only one call. 
    // Please note that the datasource fetch call is async, so we must use it's results within the fetch function.
    dataSource.fetch(function () {

        var numberOfItems = dataSource.total();

        if (numberOfItems == 0) {
            // If 0 items are returned show the label that says there are no items
            $("#myGrid").append("<p><label style='font-size: small; color: red;'>-- No Items --</label></p>");
        }
        else {
            $("#myGrid").kendoGrid({
                dataSource: dataSource,
                height: function () {
                    return (numberOfItems >= 1 && numberOfItems <= 5) ? null : "225";
                },
                columns: [
                        { field: "StuffId", title: "Id", width: 150 },
                        { field: "Stuff", title: "Stuff", width: 150 }
                    ]
            });
        }
    });

</script>