C# 配合 Easyui DataGrid 实现增删改查 通用模板

Posted 摩塔智能科技

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 配合 Easyui DataGrid 实现增删改查 通用模板相关的知识,希望对你有一定的参考价值。

前端代码:

  <div id="dlg" class="easyui-dialog" closed="true">
        <form id="fm" method="post">
            <table style="width:100%;">
                <tr><td>标题:</td><td><input name="title" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr>
                <tr><td>关键词:</td><td><input name="keywords" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr>
                <tr><td>描述:</td><td><input name="description" class="easyui-validatebox" required="true" /> </td><td>&nbsp;</td></tr>
            </table>
        </form> 
            <div id="dlg-buttons">
                <a href="javascript:void(0)" class="easyui-linkbutton"  id="btnSave" iconcls="icon-save">保存</a>
                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="javascript:$(‘#dlg‘).dialog(‘close‘)" iconcls="icon-cancel">取消</a>
            </div>
    </div>
    <table id="dg" ></table>
    <script>
        $(#dg).datagrid({
            title: 网站文章列表,
            iconCls: icon-edit,//图标 
            width: 700,
            height: auto,
            nowrap: false,
            striped: true,
            border: true,
            collapsible: false,//是否可折叠的 
            fit: true,//自动大小 
            url: DataGrid.ashx,
            //sortName: ‘id‘, 
            //sortOrder: ‘desc‘, 
            remoteSort: false,
            idField: fldId,
            singleSelect: false,//是否单选 
            pagination: true,//分页控件 
            rownumbers: true,//行号 
            frozenColumns: [[
              { field: ck, checkbox: true }
            ]],
            //-----------------------------------------------
            toolbar: [{
                text: 添加,
                iconCls: icon-add,
                handler: function () {
                     Add();
                }
            }, -, {
                text: 修改,
                iconCls: icon-edit,
                handler: function () {
                    Edit();
                }
            }, -, {
                text: 删除,
                iconCls: icon-remove,
                handler: function () {
                    Delete();
                }
            }],
            //------------------------------------------------------
            columns: [[
            { field: id, title: 编号, width: 100 },
            {field:title,title:标题},
            {field:keywords,title:关键词},
            {field:description,title:描述,align:left}
           ]]
        });


        //设置分页控件 
        var p = $(#dg).datagrid(getPager);
        $(p).pagination({
            pageSize: 10,//每页显示的记录条数,默认为10 
            pageList: [5, 10, 15],//可以设置每页记录条数的列表 
            beforePageText: ,//页数文本框前显示的汉字 
            afterPageText: 页    共 {pages} 页,
            displayMsg: 当前显示 {from} - {to} 条记录   共 {total} 条记录,
            /*onBeforeRefresh:function(){
                $(this).pagination(‘loading‘);
                alert(‘before refresh‘);
                $(this).pagination(‘loaded‘);
            }*/
        });

        //增加
        function Add()
        {
            $("#dlg").dialog("open").dialog(setTitle, 增加新文章);
            $("#fm").form("clear");
            $("#btnSave").click(AddSubmit);//绑定保存按钮的事件
        }
        //修改
        function Edit()
        {
            var row = $("#dg").datagrid("getSelected");
            if (row) {
                $("#dlg").dialog("open").dialog(setTitle, 修改文章);
                $("#fm").form("load", row);
            }
        }

        function AddSubmit()
        {
            $("#fm").form("submit", {
                url: "DataGrid.ashx?action=add",
                onsubmit: function () {
                    return $(this).form("validate");
                },
                success: function (result) {
                    if (result == "1") {
                        $.messager.alert("提示信息", "操作成功");
                        $("#dlg").dialog("close");
                        $("#dg").datagrid("load");
                    }
                    else {
                        $.messager.alert("提示信息", "操作失败");
                    }
                }
            });
        }
        //删除
        function Delete()
        {
            var row = $(#dg).datagrid(getSelected);
            if (row) {
                $.messager.confirm(Confirm, 确定要删除这条记录吗?, function (r) {
                    if (r) {
                        $.post(DataGrid.ashx, { action:delete, id: row.id }, function (result) {
                            if (result) {
                                $(#dg).datagrid(reload).datagrid(unselectAll);    // 重新加载数据 
                            } else {
                                $.messager.show({   // 出错提示
                                    title: Error,
                                    msg: result.errorMsg
                                });
                            }
                        }, json);
                    }
                });
            }
        }
    </script>

后端代码:

 

namespace EasyuiStudy
{
    /// <summary>
    /// DataGrid 的摘要说明
    /// </summary>
    public class DataGrid : IHttpHandler
    {
        private string connstring = "";

        public void ProcessRequest(HttpContext context)
        {
            string title = context.Request["title"];
            string action = context.Request["action"];
            switch (action) 
            {
                case "add": add(context);
                             break;

                case "delete": delete(context);
                              break;

                default:query(context);
                              break;
                
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //分页查询
        private void query(HttpContext context)
        {

            string rows = context.Request["rows"];
            string page = context.Request["page"];
            int intRowCount = 10;
            int intPageIndex = 1;
            if (rows != null && rows != "0")
            {
                intRowCount = Convert.ToInt32(rows);
            }
            if (page != null && page != "0")
            {
                intPageIndex = Convert.ToInt32(page);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(MyQuery(intPageIndex, intRowCount));
        
        }
        //增加
        private void add(HttpContext context)
        {
            string title = context.Request["title"];
            string keywords = context.Request["keywords"];
            string description = context.Request["description"];

            mysqlHelper mysqldb = new MySqlHelper(connstring);
            string sql = string.Format("insert into `hdm1140428_db`.`v9_news` (title,keywords,description) values(‘{0}‘,‘{1}‘,‘{2}‘)",title,keywords,description);
            int i=mysqldb.ExecuteNonQuery(sql);

            context.Response.ContentType = "text/plain";
            context.Response.Write(i.ToString());
        }

        //删除一条记录
        private void delete(HttpContext context)
        {
            string id = context.Request["id"];

            MySqlHelper mysqldb = new MySqlHelper(connstring);
            string sql = string.Format("delete from `hdm1140428_db`.`v9_news` where id={0}",id);
            int i = mysqldb.ExecuteNonQuery(sql);


            context.Response.ContentType = "text/plain";
            context.Response.Write(i.ToString());
        }

        private string MyQuery(int PageIndex,int RowCount)
        {
            MySqlHelper mysqldb = new MySqlHelper(connstring);
            //获得总记录数 
            string sql = "select Count(*) total from `hdm1140428_db`.`v9_news`";
            DataTable dt=mysqldb.ExecuteDataTable(sql);
            int total = Convert.ToInt32(dt.Rows[0].ItemArray[0].ToString()) ;
            sql = string.Format("select *     FROM `hdm1140428_db`.`v9_news` order by id desc  limit {0},{1} ", (PageIndex - 1) * RowCount, RowCount);
            dt = mysqldb.ExecuteDataTable(sql);
            string json=EasyuiDataGrid.DataTable2Json(dt,total);
            return json;
            
        }

    }
}

 

DataTable转成DataGrid能够识别的json:

 

 public class EasyuiDataGrid
    { 
        #region dataTable转换成Json格式
        /// <summary> 
        /// dataTable转换成Json格式 
        /// </summary> 
        /// <paramname="dt"></param> 
        ///<returns></returns> 
        public static string DataTable2Json(DataTable dt,int total=-1)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"total\":");
            if (total == -1)
            {
                jsonBuilder.Append(dt.Rows.Count);
            }
            else
            {
                jsonBuilder.Append(total);
            } 
            jsonBuilder.Append(",\"rows\":[");

            for (int i = 0; i <dt.Rows.Count; i++)
            {
               jsonBuilder.Append("{");
                for (int j = 0; j <dt.Columns.Count; j++)
                {
                   jsonBuilder.Append("\"");
                   jsonBuilder.Append(dt.Columns[j].ColumnName);
                   jsonBuilder.Append("\":\"");
                   jsonBuilder.Append(dt.Rows[i][j].ToString());
                   jsonBuilder.Append("\",");
                }
                if (dt.Columns.Count > 0)
                {
                   jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
               jsonBuilder.Append("},");
            }
            if (dt.Rows.Count > 0)
            {
               jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            }
            jsonBuilder.Append("]}");  
            return jsonBuilder.ToString();
        }
        #endregion dataTable转换成Json格式
    }

 

以上是关于C# 配合 Easyui DataGrid 实现增删改查 通用模板的主要内容,如果未能解决你的问题,请参考以下文章

jQuery easyUI 使用 datagrid 表格

Easyui datagrid 实现表格记录拖拽

jQuery EasyUI DataGrid在MVC中的运用-基本属性并实现分页

在easyui datagrid中双击事件怎么实现

EasyUI中datagrid的查询实现

C#将datatable生成easyui的绑定tree 的json数据格式