0

我有一个使用 kendo ui 和 asp.net mvc4 razor.in 开发的网格。在那里我使用了 kendo 网格的 html 语法而不是 asp.net mvc。

这是我的网格的代码

    <div id="example" class="k-content">
    <div id="batchgrid">
    </div>
</div>
<script type="text/javascript" lang="javascript">
    $("#batchGrid").click(function () {
        var crudServiceBaseUrl = "http://demos.kendoui.com/service",
                        dataSource = new kendo.data.DataSource({
                            transport: {
                                read: {
                                    url: crudServiceBaseUrl + "/Products",
                                    dataType: "jsonp"
                                },
                                update: {
                                    url: crudServiceBaseUrl + "/Products/Update",
                                    dataType: "jsonp"
                                },
                                destroy: {
                                    url: crudServiceBaseUrl + "/Products/Destroy",
                                    dataType: "jsonp"
                                },
                                create: {
                                    url: crudServiceBaseUrl + "/Products/Create",
                                    dataType: "jsonp"
                                },
                                parameterMap: function (options, operation) {
                                    if (operation !== "read" && options.models) {
                                        return { models: kendo.stringify(options.models) };
                                    }
                                }
                            },
                            batch: true,
                            pageSize: 20,
                            schema: {
                                model: {
                                    id: "ProductID",
                                    fields: {
                                        ProductID: { editable: false, nullable: true },
                                        ProductName: { validation: { required: true} },
                                        UnitPrice: { type: "number", validation: { required: true, min: 1} },
                                        UnitsInStock: { type: "number", validation: { min: 0, required: true} },
                                        Discontinued: { type: "boolean" },
                                        TotalStock: { type: "number" }
                                    }
                                }
                            },
                            //                            group: {
                            //                                field: "UnitPrice", aggregates: [
                            //                                        { field: "UnitPrice", aggregate: "sum" },
                            //                                        { field: "TotalStock", aggregate: "sum" }
                            //                                     ]
                            //                            },
                            aggregate: [{ field: "TotalStock", aggregate: "sum"}]

                        });

        $("#batchgrid").kendoGrid({
            dataSource: dataSource,
            dataBound: onDataBound,

            navigatable: true,

            filterable: {
                messages: {
                    and: "And",
                    or: "Or",
                    filter: "Apply filter",
                    clear: "Clear filter",
                    info: "Filter by"
                },
                extra: false, //do not show extra filters
                operators: { // redefine the string operators
                    string: {
                        contains: "Contains",
                        doesnotcontain: "Doesn't contain",
                        startswith: "Starts With",
                        endswith: "Ends"
                    },
                    number: {
                        eq: "Is Equal To",
                        neq: "Not equal to",
                        gte: "Greater than or equal to",
                        lte: "Less than or equal to",
                        gt: "Greater than",
                        lt: "Less than"
                    }
                }
            },

            reorderable: true, //not working

            selectable: "multiple",

            pageable: {
                refresh: true,
                pageSizes: [5, 10, 20, 50, 100]
            },

            height: 430,
            width: 300,

            toolbar: [
                    {
                        name: "my-create",
                        text: "Add new record"
                    },
                    {
                        name: "save",
                        text: "save changes"
                    },
                    {
                        name: "cancel",
                        text: "cancel changes"
                    },
                    {
                        name: "export",
                        text: "Export To Excel"
                    }
            ],

            columns: [
            //                            { field: "ProductID", title: "No", width: "90px" },
                            {title: "No", template: "#= ++record #", width: 45 },
                            { field: "ProductName", title: "Product Name", width: "350px" },
                            { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
                            { field: "UnitsInStock", title: "Units In Stock", width: "150px" },
                            { field: "Discontinued", title: "Purchase", width: "110px" },
                            { field: "TotalStock", title: "Total Stock", width: "150px", footerTemplate: "Total : #= kendo.toString(sum, 'C') #", format: "{0:c2}" }
            //{ command: ["destroy"], title: "&nbsp;", width: "175px" }
            ],


            export: {
                cssClass: "k-grid-export-image",
                title: "people",
                createUrl: "/Home/ExportToExcel",
                downloadUrl: "/Home/GetExcelFile"
            },

            groupable: {
                messages: {
                    empty: "Drop columns here"
                }
            }, //not working

            columnMenu: {
                sortable: true,
                filterable: true,
                messages: {
                    columns: "Hide/Show Columns",
                    filter: "Apply filter",
                    sortAscending: "Sort (asc)",
                    sortDescending: "Sort (desc)"
                }
            },

            resizable: true,

            dataBinding: function () {
                record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
            },

            sortable: {
                mode: "multiple"
            },
            sort: { field: "ProductID", dir: "asc" },

            editable: { mode: "incell", createAt: "bottom" }
        });

        //custom global variables
        newRowAdded = false;
        checkedOnce = false;

        var grid = $("#batchgrid").data("kendoGrid");
        $(".k-grid-my-create", grid.element).on("click", function (e) {

            window.newRowAdded = true;

            var dataSource = grid.dataSource;
            var total = dataSource.data().length;
            dataSource.insert(total, {});
            dataSource.page(dataSource.totalPages());
            grid.editRow(grid.tbody.children().last());
        });

        grid.bind("saveChanges", function () {
            window.newRowAdded = false;
            //                        var grid = $("#batchgrid").data("kendoGrid");
            //                        grid.dataSource.sort({ field: "ProductID", dir: "asc" });
            //            GetValOf();

            //            var grid = $('#batchgrid').data("kendoGrid");
            //            var total = 0;
            //            $.each(grid.dataSource.view(), function () {
            //                total += this.TotalStock;
            //            });
            //            alert(total);
        });

        grid.bind("cancelChanges", function () {
            window.newRowAdded = false;
        });

        $(".k-grid-export", "#batchgrid").bind("click", function (ev) {
            // your code
            //            alert("Hello");
            var grid = $("#batchgrid").data("kendoGrid");
            grid.dataSource.pageSize(parseInt($("#batchgrid").data("kendoGrid").dataSource.data().length));
            excelImport();
        });
    });
</script>

但我得到了一些用于将网格数据导入 excel 的示例代码,并且在那里他们使用了 asp.net mvc 语法。

这是代码。

@(
 Html.Kendo().Grid(Model).Name("Grid")
                .DataSource(ds => ds.Ajax()
                                .Model(m =>
                                {
                                    m.Id(p=>p.ProductID);                              
                                })
                        .Read(r => r.Action("Read", "Home"))
                )
                .ToolBar(toolBar => 
                    toolBar.Custom()
                        .Text("Export To Excel")
                        .HtmlAttributes(new { id = "export" })
                        .Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
                )
                .Columns(columns =>
                {
                    columns.Bound(p => p.ProductID);
                    columns.Bound(p => p.ProductName);
                    columns.Bound(p => p.UnitPrice).Format("{0:c}");
                    columns.Bound(p => p.QuantityPerUnit);
                })
                .Events(ev => ev.DataBound("onDataBound"))
                .Pageable()
                .Sortable()
                .Filterable()
)

但我的问题是我需要将下面的代码行添加到我的网格中(在上面提到的第一个代码中)。

.ToolBar(toolBar => 
                        toolBar.Custom()
                            .Text("Export To Excel")
                            .HtmlAttributes(new { id = "export" })
                            .Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
                    )

但我坚持这一行

.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))

有人可以告诉我如何在我的 html 网格中使用此代码..

4

1 回答 1

0

编写工具栏手册

<div class="k-toolbar k-grid-toolbar k-grid-top">
        <a class="k-button k-button-icontext " id="exportCsv" href="/Home/ExportToCsv?take=50&amp;skip=0&amp;page=1&amp;pageSize=10&amp;filter=~&amp;sort=" id="exportToCSV"><span></span>Export CSV</a>
        <a class="k-button k-button-icontext " id="exportXls" href="/Home/ExportToXls?take=50&amp;skip=0&amp;pageSize=10&amp;filter=~&amp;sort=" id="exportToExcel"><span></span>Export Excel</a>  
</div>

然后将数据绑定添加到 kendoGrid

....
            editable: false, // enable editing          
            sortable: true,
            filterable: true,
            scrollable: false,
            dataBound: onDataBound,
            columns: [..... 

然后编写'onDataBound'函数

<script>

    function onDataBound(e) {
        var grid = $('#grid').data('kendoGrid');

        var take = grid.dataSource.take();
        var skip = grid.dataSource.skip();
        var page = grid.dataSource.page();
        var sort = grid.dataSource.sort();
        var pageSize = grid.dataSource.pageSize();
        var filter = JSON.stringify(grid.dataSource.filter());        

        // Get the export link as jQuery object
        var $exportLink = $('#exportXls');

        // Get its 'href' attribute - the URL where it would navigate to
        var href = $exportLink.attr('href');

        // Update the 'take' parameter with the grid's current page
        href = href.replace(/take=([^&]*)/, 'take=' + take || '~');

        // Update the 'skip' parameter with the grid's current page
        href = href.replace(/skip=([^&]*)/, 'skip=' + skip || '~');

        // Update the 'page' parameter with the grid's current page
        href = href.replace(/page=([^&]*)/, 'page=' + page || '~');

        // Update the 'sort' parameter with the grid's current sort descriptor
        href = href.replace(/sort=([^&]*)/, 'sort=' + sort || '~');

        // Update the 'pageSize' parameter with the grid's current pageSize
        href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + pageSize);

        //update filter descriptor with the filters applied

        href = href.replace(/filter=([^&]*)/, 'filter=' + (filter || '~'));

        // Update the 'href' attribute
        $exportLink.attr('href', href);

        $('#exportCsv').attr('href', href.replace('ExportToXls', 'ExportToCsv'));
    }
</script>

这是动作和参数

      public FileResult ExportToXls(int take, int skip, IEnumerable<Sort> sort, string filter)
        {
            try
            {
                Filter objfilter = JsonConvert.DeserializeObject<Filter>(filter);

                var lstContactFormData = XmlData.GetIletisimBilgileri().OrderByDescending(i => i.tarih);

                //Get the data representing the current grid state - page, sort and filter
                //IEnumerable products = _db.Products.ToDataSourceResult(request).Data;
                IEnumerable contactsDatas = lstContactFormData.AsQueryable().ToDataSourceResult(take, skip, sort, objfilter).Data;

...
...
于 2013-09-19T13:01:53.830 回答