Javascript Kendo 数据源调用 MVC Controller

Javascript Kendo Datasource calling MVC Controller

本文关键字:MVC Controller 调用 数据源 Kendo Javascript      更新时间:2023-09-26

有时我喜欢使用Kendo框架的HTML5/Javascript实现,因为你可以更轻松地完成一些事情。在这种情况下,我需要知道结果的数量,以便我可以显示或不显示剑道网格,但是其他时候我需要根据客户端的用户输入修改数据源。不幸的是,您无法使用 MVC 包装器获取结果数量或修改数据源(据我所知)。如何使用 Kendo 数据源的 Javascript 实现调用控制器?

我能够使用以下代码使其工作:

控制器:

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>