easyui datagrid

 JQUERY 1.7.1    easyui-1.2.5

前台:

 <script type="text/javascript">
        $(document).ready(function () {
            //绑定datagrid
            $('#test').datagrid({
                title: 'EasyUi',
                //为title添加css
                iconCls: 'icon-save',
                width: 700,
                height: 350,
                //是否折叠
                collapsible: true,
                url: 'ASHX/A_EasyUi.ashx?M=GetJson',
                //数据在一行显示
                nowrap: false,
                //行条纹化
                striped: true,
                //固定序号
                rownumbers: true,
                //是否可以多选
                singleSelect: false,

                sortName: 'ID',
                sortOrder: 'desc',
                remoteSort: false,
                idField: 'ID',

                loadMsg: '正在加载,请稍后。。。',
                //是否显示分页
                pagination: true,
                //固定列
                frozenColumns: [[{ field: 'ck', checkbox: true }, { field: 'ID', title: '编号', width: 100, sortable: true, align: 'center'}]],
                //可动列
                columns: [[{ field: 'Names', title: '姓名', width: 100, align: 'center' },
                            { field: 'Adress', title: '地址', width: 100, align: 'center' },
                            { field: 'opt', title: '操作', width: 100, align: 'center', rowspan: 2, formatter: function (value, row, index) { return '<span style="color:red"><a href="" οnclick="aa(' + row.ID + ');">编辑</a> 删除</span>'; } }
                         ]],
                toolbar: [{ text: '添加', iconCls: 'icon-add', handler: function () { DisplayDialog(); } }, '-', { text: '修改', iconCls: 'icon-save', handler: function () { DisEdit(); } }, '-', { text: '删除', iconCls: 'icon-remove', handler: function () { DelFun(); } }]
            });

            //设置分页控件属性
            var p = $('#test').datagrid('getPager');
            $(p).pagination({
                pageSize: 10,
                pageList: [10, 15, 20, 25, 30],
                beforePageText: '第',
                afterPageText: '页  共{pages}页',
                displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
            });

        });

        //设置一个全局URL
        var url;

        //添加弹出窗口
        function DisplayDialog() {
            $('#dlg').css('display', 'block');
            url = 'ASHX/A_EasyUi.ashx';
            $("#dlg").dialog({
                title: '用户添加',
                modal: true,
                collapsible: true,
                resizable: true
            });
            //去掉所有Input为text的内容
            $('input').each(function () {
                if ($(this).attr('type') == 'text') {
                    $(this).attr('value', '');
                }

            });
        }
        //修改弹出窗口
        function DisEdit() {
            //通过getSelected取出一行的所有信息
            var row = $('#test').datagrid('getSelected');
            var rows = $('#test').datagrid('getSelections');
            if (row) {
            //判断是否多选
                if (rows.length > 1) {
                    $.messager.alert('Warning', '请不要多选');
                }
                else {
                    $('#dlg').css('display', 'block');
                    url = 'ASHX/A_EasyUi.ashx?id=' + row.ID;
                    $("#dlg").dialog({
                        title: '用户修改',
                        modal: true,
                        collapsible: true,
                        resizable: true
                    });
                    //赋值
                    $('#username').attr('value', row.Names);
                    $('#Sex').attr('value', row.Sex);
                    $('#Adress').attr('value', row.Adress);
                }
            }
            else {
                $.messager.alert('Warning', '请选择');
            }
        }
        //添加,修改执行方法
        function AddFuc() {
            $.ajax({
                type: 'post',
                url: url,
                data: { M: "Ins", Names: $('#username').val(), Sex: $('#Sex').val(), Adress: $('#Adress').val() },
                success: function (msg) { $('#dlg').dialog('close'); $('#test').datagrid('reload'); }
            });
        }
        //删除方法
        function DelFun() {
            url = 'ASHX/A_EasyUi.ashx';
            var row = $('#test').datagrid('getSelected');
            var rows = $('#test').datagrid('getSelections');
            //是否选择,也可以用if(row)来判断(一个返回null一个返回array)
            if (rows.length > 0) {
                var ids = [];
                for (var i = 0; i < rows.length; i++) {
                    //每行ID放入数组中
                    ids.push(rows[i].ID);
                }
                //必须为string类型,不然传不过去
                var aa = ids.toString();
                $.ajax({
                    type: 'post',
                    url: url,
                    data: { M: 'Del', ID: aa },
                    success: function (msg) { $('#test').datagrid('reload'); $('#test').datagrid('clearSelections'); } //设置可以多选后,删除一条后再删除一条会提示删除两条,实际上只删除了一条,已经删除的那一条没有清空 

                });

            }
            else {
                $.messager.alert('Warning', '请选择');
            }
        }

        //最后一列的编辑方法
        function aa(index) {
            alert(index);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table id="test">
    </table>
    <div id="dlg" style="width: 400px; height: 400px; display: none">
        用户名:<input type="text" id="username" /><br />
        性别:<input type="text" id="Sex" /><br />
        地址:<input type="text" id="Adress" /><br />
         <input type="button" value="提交" οnclick="AddFuc()" /><input type="button" value="关闭"
            οnclick="javascirpt:$('#dlg').dialog('close')" />
    </div>
    </form>
</body>


ASHX:

 public class A_EasyUi : IHttpHandler
    {
        /// <summary>
        /// 分页前台传来两个值,传回去一个total一个数据
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string Method = context.Request.Params["M"];
            switch(Method)
            {
                case "GetJson":
                    //row和page从前台传来
                    //每页多少条数据
                    int row = int.Parse(context.Request["rows"].ToString());                 
                    //当前第几页
                    int page = int.Parse(context.Request["page"].ToString());
                    //总共多少条数据
                    int i = Count();
                    ReturnJson(context, row, page); 
                    break;
                case "Ins":
                    AddUser(context.Request.Params["id"], context.Request.Params["Names"], context.Request.Params["Sex"], context.Request.Params["Adress"]);
                    break;
                case "Del":
                    string ss = context.Request.Params["ID"];
                    DeleteMessage(context.Request.Params["ID"]);
                    break;

            }
        }
        //json序列化1
        public string ConvertDTToJson(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"total\":" + Count() + ",");//作为传给前台的total域,放置一共多少条数据
                JsonString.Append("\"rows\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        //json序列化2
        public string MStoJson(DataTable dt)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ArrayList dic = new ArrayList();
            foreach (DataRow row in dt.Rows)
            {
                Dictionary<string, object> drow = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    drow.Add(col.ColumnName, row[col.ColumnName]);
                }
                dic.Add(drow);
            }
            return jss.Serialize(dic);
        }

        //初始化绑定数据
        public void ReturnJson(HttpContext context, int pageSize, int CurrentPageIndex)
        {
            string SqlStr = "select top " + pageSize + " * from (SELECT ROW_NUMBER() OVER (ORDER BY ID desc) AS RowID,* FROM Jquery) as Temp_tb where RowID>" + pageSize + " * (" + CurrentPageIndex + " - 1)";
            DataSet ds = MyClass.SqlHelper.ExcuteDataSet(MyClass.SqlHelper.ConnectionString, SqlStr);
            DataTable dt = ds.Tables[0];
            string dd = ConvertDTToJson(dt);
            context.Response.Write(dd);
        }
        //添加数据
        public void AddUser(object ContextID,string Names,string Sex,string Adress)
        {
            if (ContextID != null)
            {
                string SqlStr = "update Jquery set Names=@Names,Sex=@Sex,Adress=@Adress where ID=@ID";
                SqlParameter[] sqlparm = {
                                         new SqlParameter("@ID",SqlDbType.Int),
                                         new SqlParameter("@Names",SqlDbType.NVarChar,50),
                                         new SqlParameter("@Sex",SqlDbType.NVarChar,50),
                                         new SqlParameter("@Adress",SqlDbType.NVarChar,50)
                                         };
                sqlparm[0].Value = Convert.ToInt32(ContextID);
                sqlparm[1].Value = Names;
                sqlparm[2].Value = Sex;
                sqlparm[3].Value = Adress;
                MyClass.SqlHelper.ExcuteNonQuery(MyClass.SqlHelper.ConnectionString, CommandType.Text, SqlStr, sqlparm);
            }
            else
            {
                string SqlStr = "insert into Jquery(Names,Sex,Adress) values (@Names,@Sex,@Adress)";
                SqlParameter[] sqlparm = {
                                         new SqlParameter("@Names",SqlDbType.NVarChar,50),
                                         new SqlParameter("@Sex",SqlDbType.NVarChar,50),
                                         new SqlParameter("@Adress",SqlDbType.NVarChar,50)
                                         };
                sqlparm[0].Value = Names;
                sqlparm[1].Value = Sex;
                sqlparm[2].Value = Adress;
                MyClass.SqlHelper.ExcuteNonQuery(MyClass.SqlHelper.ConnectionString, CommandType.Text, SqlStr, sqlparm);
            }
        }

        //删除数据
        public void DeleteMessage(string ID)
        {
            //返回数组
            string[] split = ID.Split(new Char[] { ',' });
            foreach (string s in split)
            {
                string Split_id = s;
                string SqlStr = "delete from Jquery where id=@id";
                SqlParameter[] sqlparm = { 
                                     new SqlParameter("@id",SqlDbType.Int)
                                     };
                sqlparm[0].Value = Convert.ToInt32(Split_id);
                MyClass.SqlHelper.ExcuteNonQuery(MyClass.SqlHelper.ConnectionString, CommandType.Text, SqlStr, sqlparm);
            }
        }
        //取出所有条数
        public int Count()
        {
            object i = MyClass.SqlHelper.ExcuteScalar(MyClass.SqlHelper.ConnectionString, CommandType.Text, "select count(*) from Jquery", null);
            return Convert.ToInt32(i);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值