天天看點

KendoUI Grid Demo代碼

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Kendo.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title></title>

    <link href="kendo/styles/kendo.common.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />

    <link href="kendo/styles/kendo.default.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />

    <link href="kendo/styles/kendo.default.mobile.min.css" target="_blank" rel="external nofollow" rel="stylesheet" />

    <script src="kendo/js/jquery.min.js"></script>

    <script src="kendo/js/kendo.all.min.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div id="example">

            <input type="text" id="name" name="name" class="k-textbox" style="width: 200px;" />

            <a id="search" href="javascript:void(0);" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >查詢</a>

            <div id="grid"></div>

            <script id="template" type="text/x-kendo-template">

                 <a class="k-button" href="javascript:void(0);" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" οnclick="eidtbtn()">Edit</a>

            </script>

            <script>

                function eidtbtn() {

                    var cust_grid = $("#grid").data("kendoGrid");

                    var selectrow = cust_grid.items().index(cust_grid.select()) + 1;

                    cust_grid.editRow($("#grid tr:eq(" + selectrow + ")"));

                }

                $(function () {

                    var grid = $("#grid").kendoGrid({

                        height: 550,

                        columns: [

                                { selectable: true, width: '45px' },

                                { field: "id", title: "編号", width: 200 },

                                { field: "name", title: "姓名", width: 200 },

                        ],

                        groupable: false,

                        sortable: true,

                        dataSource: {

                            transport: {

                                read: "http://localhost:54386/Handler.ashx",

                                update: "http://localhost:54386/AddHandler.ashx",

                                dataType: "json",

                                parameterMap: function (data, type) {

                                    //排序

                                    if (data.sort) {

                                        var sortObj = data.sort[0];

                                        data.dir = sortObj.dir;

                                        data.field = sortObj.field;

                                    } else {

                                        data.field = "id";

                                        data.dir = "desc";

                                    }

                                    return data;

                                }

                            },

                            serverPaging: true,

                            serverSorting: true,

                            serverFiltering: true,

                            schema: {

                                data: function (response) {

                                    var json = eval('(' + response + ')');

                                    return eval('(' + json.data + ')');

                                },

                                total: function (response) {

                                    var json = eval('(' + response + ')');

                                    return json.total;

                                },

                                model: {

                                    id: 'id',

                                    fields: {

                                        id: { type: 'string' },

                                        name: { type: 'string' },

                                    }

                                }

                            }

                        },

                        toolbar: [

                               { name: 'create' },

                               { template: '<a class="k-button k-button-icontext" href="javascript:DelDemo();" target="_blank" rel="external nofollow" ><span class="k-icon k-i-x"></span>批量删除</a>' },

                               { template: kendo.template($("#template").html()) }

                               //{ name: 'excel' },

                               //{ name: 'pdf' },

                               //{ name: 'search' },

                               //{ name: 'save' },

                               //{ name: 'cancel' }

                        ],

                        editable: {

                            mode: 'popup',

                            window: {

                                width: '88%',

                                height: '40%'

                            },

                            template: kendo.template($('#editTemplate').html()),

                            confirmation: false

                        },

                        edit: function (e) {

                            if (e.model.id == '') {

                                e.container.kendoWindow('title', '新增');

                            } else {

                                e.container.kendoWindow('title', '編輯');

                            }

                        },

                        pageable: {

                            refresh: true,

                            pageSizes: true,

                            buttonCount: 5,

                            page: 1,

                            pageSize: 2,

                            pageSizes: [100, 200, 300],

                            messages: {

                                display: "顯示 {0}-{1} 共 {2} 項",

                                empty: "沒有資料",

                                itemsPerPage: "每面顯示數量",

                                first: "第一頁",

                                last: "最後一頁",

                                next: "下一頁",

                                previous: "上一頁"

                            }

                        }

                    });

                    grid.on('click', '.k-grid-content tr', function (e) {

                        var gd = grid.data("kendoGrid"); //#user_table是資料集

                        var foundrow = gd.tbody.find("tr:eq(" + e.currentTarget.rowIndex + ")"); //use that to find the row

                        var xx = foundrow.find("input").get(0).checked;

                        debugger;

                        if (xx) {

                            //foundrow.find("input").click();//取消選中

                        } else {

                            gd.select(foundrow); //預設選中資料

                        }

                        //if (this.select().find('input[type=checkbox]').attr('checked')) {

                        //    this.select().find('input[type=checkbox]').removeAttr('checked');

                        //} else {

                        //    this.select().find('input[type=checkbox]').attr('checked', 'true');

                        //}

                        //失敗

                        //設定單機列選中行

                        //grid.select(e.currentTarget.rowIndex);

                        // 擷取目前選擇行資料

                        //var row = grid.data("kendoGrid").select();

                        //var data = grid.data("kendoGrid").dataItem(row);

                        //var Name = data.name;

                    });

                    $("#search").click(function () {

                        var name = $("#name").val();

                        grid.data("kendoGrid").dataSource.filter([

                            { field: "name", value: name }

                        ]);

                    });

                });

            </script>

        </div>

    </form>

    <div class="k-loading-image" id="loading" style="display: none;"></div>

    <script id="editTemplate" type="text/x-kendo-template">

        <form id="editForm">

            <input name="id" type="hidden">

            <div class="form-row">

                <div class="form-group col-sm-6 col-md-4 col-lg-3 col-xl-2">

                    <label class="d-block"><strong class="k-required">*</strong>姓名:</label>

                    <input class="k-textbox w-100" name="name" type="text" placeholder="文本框" required data-required-msg="請輸入使用者名!"

         pattern="[A-Za-z0-9]{4,16}" data-pattern-msg="請輸入4-16個大小寫字母或數字!">

                </div>

                <div class="form-group col-sm-6 col-md-4 col-lg-3 col-xl-2">

                    <label class="d-block"><strong class="k-required">*</strong>編碼:</label>

                    <input class="k-textbox w-100" name="id" type="text" placeholder="文本框" required data-required-msg="請輸入姓名!"

         pattern="[\\\u4E00-\\\u9FA5]{1,10}" data-pattern-msg="請輸入1-10個漢字!">

                </div>

            </div>

        </form>

    </script>

    <script type="text/javascript">

        // 批量删除ID

        function DelDemo() {

            //選中的ID

            var ids = $('#grid').data('kendoGrid').selectedKeyNames();

            if (ids.length > 0) {

                //等待框搞定

                //$('#loading').show();

                //$('#loading').hide();

                //重新整理表格

                $('#grid').data('kendoGrid').dataSource.read();

            } else {

                alertMsg('請先選擇對象!', 'warning');

            }

        }

        // 警告框

        function alertMsg(msg, type, closed) {

            var alertDialog = $('<div class="dialog-box"></div>').kendoDialog({

                animation: { open: { effects: 'fade:in' }, close: { effects: 'fade:out' } },

                closable: false,

                maxWidth: '30%',

                maxHeight: '30%',

                minWidth: 320,

                minHeight: 195,

                title: '資訊',

                content: '<dl class="d-flex align-items-center m-0"><dt>' + checkInfoType(type) + '</dt><dd class="m-0">' + msg + '</dd></dl>',

                actions: [

                    {

                        text: '确定',

                        primary: true,

                        action: function (e) {

                            if (closed) {

                                closed();

                            }

                            alertDialog.close();

                        }

                    }

                ],

                close: function () {

                    alertDialog.destroy();

                }

            }).data('kendoDialog');

            alertDialog.open();

        }

        // 資訊類型判斷

        function checkInfoType(type) {

            if (type === 'success') {

                return '<i class="fas fa-check-circle"></i>';

            } else if (type === 'info') {

                return '<i class="fas fa-info-circle"></i>';

            } else if (type === 'question') {

                return '<i class="fas fa-question-circle"></i>';

            } else if (type === 'warning') {

                return '<i class="fas fa-exclamation-circle"></i>';

            } else if (type === 'error') {

                return '<i class="fas fa-times-circle"></i>';

            } else {

                return '';

            }

        }

        // { command: ["edit", "destroy"], title: "&nbsp;", width: "250px" }],

        表格自适應高度:1

        //window.onresize = function () {

        //    $('#grid').data('kendoGrid').refresh();

        //};

        //2

        //this.size();

        //$(window).resize(function () {

        //    that.size();

        //});

        //size: function () {

        //    var headerHeight = $(".layui-header").outerHeight();

        //    var tabsHeight = $("#LAY_app_tabs").outerHeight();

        //    var toolbarHeight = $(this.dv).find('.toolbar').outerHeight() + 15;

        //    var gridheight = window.innerHeight - headerHeight - tabsHeight - toolbarHeight - 2 * 15;

        //    var otherElements = this.grid.children().not(".k-grid-content"), otherElementsHeight = 0;

        //    otherElements.each(function () {

        //        otherElementsHeight += $(this).outerHeight();

        //    });

        //    var dataArea = this.grid.find(".k-grid-content");

        //    dataArea.height(gridheight - otherElementsHeight - 2);

        //}

    </script>

</body>

</html>

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace Kendo

{

    /// <summary>

    /// Handler 的摘要說明

    /// </summary>

    public class Handler : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            int take = Convert.ToInt32(context.Request.QueryString["take"]);

            int skip = Convert.ToInt32(context.Request.QueryString["skip"]);

            string page = context.Request.QueryString["page"];

            string pageSize = context.Request.QueryString["pageSize"];

            string dir = context.Request.QueryString["dir"];

            string field = context.Request.QueryString["field"];

            //查詢

            var querys = context.Request.QueryString.AllKeys.Where(m => m.StartsWith("filter[filters]"));

            //計算查詢請求時查詢參數的個數

            var queryCount = querys.Count(m => m.EndsWith("[field]"));

            var dicSearch = new Dictionary<string, object>();//定義變量存儲查詢的字段和值

            for (int i = 0; i < queryCount; i++)

            {

                //查詢字段和對應的值存儲在一個字典中

                dicSearch.Add(context.Request.QueryString["filter[filters][" + i + "][field]"],

                    context.Request.QueryString["filter[filters][" + i + "][value]"]);

            }

            context.Response.Write(JsonConvert.SerializeObject(new { error="",

                data = JsonConvert.SerializeObject(DB.DBList.Skip(skip).Take(take).ToList()), total = DB.DBList.Count }));

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace Kendo

{

    /// <summary>

    /// AddHandler 的摘要說明

    /// </summary>

    public class AddHandler : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";

            string id = context.Request.QueryString["id"];

            string name = context.Request.QueryString["name"];

            var dm = new Demo { id = id, name = name };

            DB.DBList.Add(dm);

            context.Response.Write(JsonConvert.SerializeObject(dm));

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}