KendoUI 简单增,删,改,查操作

界面:

班级表

学生表

年级表

框架

框架HTML代码

<div id="splittle">
    <div id="left">
       <div id="Student_Tree"></div>
    </div>
    <div id="right">
        <div id="gridview"></div>
    </div>
</div>

<div id="Student_Tree"></div>  这是 左边的树形控件的HTML代码

<div id="Gridview"></div>          这是右边表格控件的HTML代码

框架JavaScript代码

<script>
    var demoConditions = "";
    var Class_ID = 1;
    $("#splittle").kendoSplitter({
        panes: [
            { collapsible: true, size: '20%' },
            { collapslible: true }
        ]
    })
</script>

一。显示数据库中学生的信息

使用 KendoUI 中的 Grid组件进行渲染

首先要通过后台获取数据库中的数据

var datasource = new kendo.data.DataSource({
        pageSize: 2,  //一页显示几条数据
        batch: true,
        pageable: true,
        serverSrting: true,
        serverPaging: true,
        sort: [{ field: "StudentNum", dir: "desc" }], //排序 field 排序字段 dir 升序降序
        schema: {                                    //Object远程数据解析配置
            data: "rows",                      //这是接受所有的数据
            total: "total",               //总数据的行数
            model: {
                id: "StudentID",
                fields: {
                    StudentNum: { type: 'int' }
                }
            }
        },
        transport: {
            read: {
                url: "/Home/Select",  //后台地址
                type: "post",
                datatype: "json"
            },
            parameterMap: function (options, operation) { //传给后台的参数
                if (operation == "read") {
                    return {
                        conditions:demoConditions,  //查询条件
                        page: options.page,     //第几页
                        pageSize: options.pageSize,  //一页显示几条数据
                        Class_ID: Class_ID           //当前选择的班级编号
                    }
                }
            }
        },
    })

然后再创建Grid

var grid = $("#gridview").kendoGrid({
        height:"300px",   //高度
        dataSource: datasource,  //创建的数据源
        toolbar: [
            { template: kendo.template($("#gridbar").html()) } //头部按钮  template: 绑定模板
        ],
        selectable: "single",  //单选
        headerCenter: true,
        rowNumber: true,
        srollable: true,
        pageable: {
            pageSizes: [1, 2, 3, 5],   //一页显示几条数据 的选择项
            refresh: true,
            buttonCount: 5
        },
        sortable: true,
        resizable: true,
        serverPaging: true,
        columns: [                                       //绑定数据源中的数据的字段名  field: 字段名 title:表头名称
            { field: "StudentName", title: "姓名" },
            { field: "StudentNum", title: "学号" },
            { field: "StudentSex", title: "性别" }
        ],
        columnMenu: true,
    }).data("kendoGrid");

Grid 中 toolbar 模板的代码

<script id="gridbar" type="text/x-kendo-template">
    <div id="gridmenu" style="float:left;margin-right:3px;margin-top:2px;">
        <form id="searchform">
            姓名:<input type="text" id="s_demo_title" name="StudentName" class="k-textbox" />&nbsp;
            <button type="button" id="btnSearch" class="k-button"><span class="glyphicon glyphicon-search"></span>查询</button>
        </form>
    </div>
    <div id="operate" style="float:right;margin-right:3px;margin-top:2px;">
        <button id="btnAdd" class="k-button k-button-icontext k-grid-add">新增</button>
        <button id="btnEdit" class="k-button k-button-icontext k-grid-add">修改</button>
        <button id="btnDelete" class="k-button k-button-icontext k-grid-add">删除</button>
    </div>
</script>

后代代码

        public ActionResult Select(int page, int pageSize,string conditions="杨",int Class_ID=1,int Grade_ID=1)//初始值
        {
            using (_9_30_kendoUI_初试.Models.StudentDBEntities db = new Models.StudentDBEntities()) {
                var s = from C1 in db.Class //LinQ查询 三张表
                        join G1 in db.Grade
                        on C1.Grade_ID equals G1.Grade_ID
                        join S1 in db.Students
                        on C1.Class_ID equals S1.Class_ID
                        where S1.Students_Name.Contains(conditions) //模糊查询
                        && C1.Class_ID==Class_ID 
                        select new
                        {
                            StudentID=S1.Students_ID,
                            StudentName = S1.Students_Name,
                            StudentSex = S1.Students_Sex,
                            StudentNum = S1.Students_Num
                        };
                var result = s.ToList().Skip(pageSize * (page - 1)).Take(pageSize); //分页
                var obj = new { total = s.ToList().Count, rows = result };
                return Json(obj,JsonRequestBehavior.AllowGet);
            }
        }

二。查询

根据输入的姓名模糊查询

    $("#btnSearch").click(function () {
        var btnSearch = $("#s_demo_title").val();//获取文本框中的文本
        demoConditions = btnSearch;  //将文本传给 数据源(dataScorce)中的 demoCondiions
        grid.dataSource.page(1);  //更新 Grid
        
    });
</script>

三。增删改

删除后台代码

   public ActionResult StudentDel(_9_30_kendoUI_初试.Models.Students s)
        {
            using (_9_30_kendoUI_初试.Models.StudentDBEntities db=new Models.StudentDBEntities()) {
                db.Students.Remove(db.Students.Find(s.Students_ID));//获取传过来的对象的ID再根据ID进行删除操作
               int result= db.SaveChanges();
                return Content(result==1?"删除成功":"删除失败");
            }
               
        }

修改后代代码

   public ActionResult StudentEdit(_9_30_kendoUI_初试.Models.Students s)
        {
            using (_9_30_kendoUI_初试.Models.StudentDBEntities db = new Models.StudentDBEntities())
            {
              _9_30_kendoUI_初试.Models.Students ss=  db.Students.Find(s.Students_ID);
                ss.Students_Name = s.Students_Name;
                ss.Students_Num = ss.Students_Num;
                ss.Students_Sex = ss.Students_Sex;
               int result= db.SaveChanges();
                return Content(result==1?"修改成功":"修改异常");
            }
        }

增加后台代码

 public ActionResult StudentAdd(_9_30_kendoUI_初试.Models.Students s) {
            using (_9_30_kendoUI_初试.Models.StudentDBEntities db = new Models.StudentDBEntities()) {
                db.Students.Add(s);
               int result= db.SaveChanges();
                return Content(result==1?"添加成功":"添加失败");
            }
            
        }

前台代码

<script>
    var editdiv = $("#editdiv").kendoWindow({  //这是新增,修改的弹窗
        width: "400px",
        heigth: "300px",
        open: function () {
            this.center();
            this.wrapper.css({ top: "5px" });
            var validator = $("#editform").data("kendovalidator");
            if (validator) {
                validator.hideMessages();
            }
        },
        title: "新增",
        modal: true,
        visible: false,
    }).data("kendoWindow");
</script>
<div id="editdiv" style="display:block"> @*这是弹窗的HTML代码*@
    <form id="editform">
        <table class="table">
            <tr>
                <td width="100px" class="tdColor" style="white-space: nowrap">姓名:<span style="color:red">*</span></td>
                <td>
                    <input id="StudentName" name="Students_Name" class="k-textbox" type="text" style="width:100%;" maxlength="50" required="required" />
                    <input name="Students_ID" style="display:none"  />
                    <input id="Class_ID" name="Class_ID" style="display:block" value="1" />
                </td>
            </tr>
            <tr>
                <td width="100px" class="tdColor" style="white-space: nowrap">性别:<span style="color:red">*</span></td>
                <td>
                    <input id="man" name="Students_Sex" class="k-radiobutton" type="radio" value="男" checked="checked" required="required" />男
                    <input id="wuman" name="Students_Sex" class="k-radiobutton" type="radio" value="女" required="required" />女
                </td>
            </tr>
            <tr>
                <td width="100px" class="tdColor" style="white-space: nowrap">学号:<span style="color:red">*</span></td>
                <td>
                    <input id="StudentNum" name="Students_Num" class="k-textbox" type="text" style="width:100%;" maxlength="50" required="required" />
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <button type="button" id="btnPro" class="k-button k-button-icontext k-grid-add"><span class="glyphicon glyphicon-ok"></span>&nbsp;保存</button>&nbsp;&nbsp;
                    <button type="reset" id="sreset" class="k-button k-button-icontext k-grid-add" style="display:none"><span class="glyphicon glyphicon-refresh"></span>&nbsp;重置</button>
                    <button type="button" id="btncancel" class="k-button k-button-icontext k-grid-add" onclick="javascript: editdiv.close()"><span class="glyphicon glyphicon-ban-circle"></span>&nbsp;取消</button>
                </td>
            </tr>
        </table>
    </form>
</div>

增删改代码

<script>
    $("#operate").on('click', 'button', function (e) {//根据ID找到这个div 再获取这个div里面的点击事件
        var btnid = this.id;     //获取当前点击按钮的id
        switch (btnid) {        //等值判断点击的是哪个按钮 再执行不同的操作
            case "btnAdd":
                openeditdiv(0);
                break;
            case "btnEdit":
                openeditdiv(1);
                break;
            case "btnDelete":
                delete_click();
                break;
            default:
                break;

        }
    })
    var editype = 0;//默认为新增
    function openeditdiv(s) {
        if (s == 0) {
            editdiv.title = "新增";
            editype = "add";
            $("#editform").trigger('reset'); //清空表单的值
        }
        else {
            editdiv, title = "修改";
            editype = "update";
            var sele = grid.select();  //获取选中的一行
            if (sele.length == 1) {
                //把数据填充到form 表单
                var dataItem = grid.dataItem(sele[0]);
                var $form = $("#editform");
                // var a=$form.autofill(dataItem);
                //  alert(a)
                $("#StudentName").val(dataItem["StudentName"]);//填充姓名
                if (dataItem["StudentSex"] == "男") {  //填充性别
                    $("#man").attr("cheched", "checked");
                }
                else {
                    $("#wuman").attr("checked", "checked");
                }
                $("#StudentNum").val(dataItem["StudentNum"]); //填充学号
                $("input[name='Students_ID']").val(dataItem["StudentID"]);//填充StudentID
            }
            else {
                alert("请选择一条要删除的数据");
                return;
            }
        }
        editdiv.open();
    }
    //-------------------保存按钮点击事件  添加和修改
    $("#btnPro").click(function (e) {
        e.preventDefault();
        var $form = $("#editform");
        var data = $form.serializeObject(); //序列化表单的值
        if (editype == "add") { //添加
            $.ajax({
                type: "get",
                url: "/Home/StudentAdd",  //添加的后台地址
                contentType: "application/json",
                data: data,            //传到后台的数据(表单填写的数据)
                beforeSend: function () {  //准备事件
                    kendo.ui.progress($form, true);    //显示请等待图片
                    $("#btnPro").attr('disabled', 'disabled'); //禁止保存按钮
                    $("#btnPro").text("保存中...");//修改该保存按钮的文本
                },
                success: function (resp) {  //返回事件
                    if (resp == "添加成功") {
                        kendo.ui.progress($form, false);//关闭请等待图片
                        alert("添加成功")
                       // grid.datasource.read();//刷新网格
                        $("#btnPro").attr('disabled', 'false');
                        $("#btnPro").text("保存");
                        editdiv.close();  //关闭弹窗
                        grid.dataSource.page(1);//刷新Grid
                    }
                    else {
                        alert(resp);
                        $("#btnPro").attr("disabled", "false");
                        $("#btnPro").text("保存");
                    }
                },
                complete: function () {//ajax 完成事件
                 
                }
            })
        } else {//修改     ---与添加差不多
            $.ajax({
                type: 'GET',
                url: "/Home/StudentEdit",
                contentType: "application/json",
                data: data,
                beforeSend: function () {
                    kendo.ui.progress($form, true);
                    $("#btnPro").attr("disabled", "true");
                    $("#btnPro").text("保存中...");
                },
                success: function (resp) {
                    if (resp == "修改成功") {
                        alert(resp)
                        editdiv.close();
                        
                        $("#btnPro").attr("disabled", "false");
                        $("#btnPro").text("保存");
                        grid.dataSource.page(1);
                    }
                    else {//修改异常
                        alert(resp)
                        $("#btnPro").attr("disabled", "false");
                        $("#btnPro").text("保存");
                    }
                },
                complete: function () {//完成事件
                    
                }

            })
        }
    })
    function delete_click() {   //删除事件
        var $form = $("#editform");
        var sele = grid.select();  // 获取要删除行
        if (sele.length == 0) {
            alert("请选择要删除的人")
            return;
        }
        var id = grid.dataItem(sele[0]).StudentID; //获取要删除的StudentID
        var student = { Students_ID: id }
        if (sele.length == 1) {                 //用ajax 传到后台 进行删除
            $.ajax({
                url: "/Home/StudentDel",
                type: "get",
                data: student,
                success: function (result) {
                    alert(result)
                    grid.dataSource.page(1); //更新Grid
                }
            })
        }
       
    }
</script>

猜你喜欢

转载自blog.csdn.net/qq_41616234/article/details/83014257