easuyui datagrid総合機能demoが実現


実現機能:行内修正、一括行に追加、多条件クエリ.(照会中は連絡ではない)
JavaScript:
          $(function(){
<span style="font-family: Arial, Helvetica, sans-serif;">                    initGrid8();</span>
<span style="font-family: Arial, Helvetica, sans-serif;">                     });</span>
          //       
          function initGrid8() {
            //   comblbox  
            initComoboxData();
            //            
            $('#txtname').textbox().textbox('addClearBtn', 'icon-clear');
            //           
            var now = new Date(); 
            var time1 = now.getFullYear()-50 + "-" + (now.getMonth()+1).toString() + "-" + now.getDate().toString();
            var time2 = now.getFullYear() + "-" + (now.getMonth() + 1).toString() + "-" + now.getDate().toString();
            $("#datebox1").datebox('setValue', time1);
            $("#datebox2").datebox('setValue', time2);
            //    
            $("#btn_save").linkbutton({ onClick: function () { grid8Accept(); return false;  }});
            //$("#btn_search").linkbutton({ onClick: function () { doSearch(); } });
            $("#cmbGender").combobox({ onChange: function () { doSearch(); } });
            //$("#deptCombobox8").combobox({ onChange: function () { doSearch(); } });
            //$("#deptCombobox8").combobox({ onChange: function () { alert(); doSearch(); } });
            //$("#datebox1").datebox({ onChange: function (nValue, oValue) { if (oValue != null && oValue != '') { doSearch(); }}});
            //  :
            $("#dg8").datagrid({
                height: 300,
                width: 800,
                title: '   demo1',
                fitColumns: true,

                toolbar: '#tb8',
                url: '/Home/grid8GetData',                
                queryParams: tbForm8Json("tbForm8"),
                rownumbers: true,
                pagination: true,

                pageNumber:1,
                sortName: 'NAME',
                sortOrder: 'desc',
                multiSort: true,
                pageList: [5,10,15,20,30,50],
                pageSize:10,
                columns: [[
                    { field: 'ck', checkbox: true },
                    { field: 'EMPID', title: '    ', width: 80, align: 'CENTER',sortable:true},
                    {
                        field: 'NAME', title: '  ', width: 120, align: 'CENTER', sortable: true,
                        editor: { type: 'text' }
                    },
                    {
                        field: 'GENDER', title: '  ', width: 80, align: 'CENTER', sortable: true,
                        editor: { type: 'combobox', options: { textField: 'label', valueField: 'value', data: [{ label: ' ', value: '1' }, { label: ' ', value: '0' }] } }
                    },
                    {
                        field: 'BIRTHDAY', title: '    ', width: 80, align: 'CENTER', sortable: true,
                        editor: { type: 'datebox' }
                    },
                    {
                        field: 'DEPTNO', title: '  ', width: 80, align: 'CENTER', sortable: true,
                        editor: {
                            type: 'combobox', options: {
                                textField: 'NAME', valueField: 'DEPTID', url: '/Home/initCombobox8Data',
                                onLoadSuccess: function (res) {
                                    var str = JSON.parse(res);
                                    if (editIndex != undefined)
                                    {
                                        var ed = $('#dg8').datagrid('getEditor', { index: editIndex, field: 'DEPTNO' });
                                        $(ed.target).combobox('loadData', str);
                                    }

                                    if (addRowsCount > 0)
                                    {
                                        var ed = $('#dg8').datagrid('getEditor', { index: 0, field: 'DEPTNO' });
                                        $(ed.target).combobox('loadData', str);                                       
                                    }
                                }
                            }
                        }
                    }
                ]],
                onLoadSuccess: function (res) {

                },
                onDblClickRow: function (index,row){
                    grid8OnClickRow(index,row);
                }

            });



        }

        //           
        $.extend($.fn.textbox.methods, {
            addClearBtn: function (jq, iconCls) {
                return jq.each(function () {
                    var t = $(this);
                    var opts = t.textbox('options');
                    opts.icons = opts.icons || [];
                    opts.icons.unshift({
                        iconCls: iconCls,
                        handler: function (e) {
                            $(e.data.target).textbox('clear').textbox('textbox').focus();
                            $(this).css('visibility', 'hidden');
                        }
                    });
                    t.textbox();
                    if (!t.textbox('getText')) {
                        t.textbox('getIcon', 0).css('visibility', 'hidden');
                    }
                    t.textbox('textbox').bind('keyup', function () {
                        var icon = t.textbox('getIcon', 0);
                        if ($(this).val()) {
                            icon.css('visibility', 'visible');
                        } else {
                            icon.css('visibility', 'hidden');
                        }
                    });
                });
            }
        });
        //       :
        function doSearch() {
            $("#dg8").datagrid('reload', tbForm8Json("tbForm8"));
        };
        //   
        function doAdd() {
            $("#dg8").datagrid('insertRow', {
                index: 0, row: {
                    EMPID: 88,

                    NAME:'',
                    GENDER:1,
                    BIRTHDAY:'',
                    DEPTNO:1
                }
            }).datagrid('selectRow', 0).datagrid('beginEdit', 0);

            if (editIndex != undefined)
            {
                editIndex += 1;
            }

            addRowsCount += 1;
        };
        //       json:
        function tbForm8Json(id) {

            var arr = $("#" + id).serializeArray()
            var jsonStr = "";

            jsonStr += '{';
            for (var i = 0; i < arr.length; i++) {
                jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",'
            }
            jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
            jsonStr += '}'

            var json = JSON.parse(jsonStr);

            return json
        }
        //combobox     
        function initComoboxData() {
            $("#deptCombobox8").combobox({
                url: '/Home/initCombobox8Data',
                valueField: 'DEPTID',
                textField: 'NAME',
                width:70,
                onLoadSuccess: function (res) {                   
                    var str = JSON.parse(res);                    
                    var a = {};
                    a.DEPTID = '-1';
                    a.NAME = "  ";
                    //       
                    str.unshift(a); 
                    $("#deptCombobox8").combobox('loadData', str); 

                },
                onChange: function (newValue,oldValue) {
                    if (oldValue != null && oldValue != '') {

                        doSearch();
                    }
                }
            })

            $('#deptCombobox8').combobox('select', '-1');

        }


   //          :
        function grid8EndEditing() {
            if (editIndex == undefined) { return true }
            if ($('#dg8').datagrid('validateRow', editIndex)) {                
                $('#dg8').datagrid('endEdit', editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        }
        //  grid        
        function grid8OnClickRow(index,row) {
            if (editIndex != index) {
                if (grid8EndEditing()) {
                    $('#dg8').datagrid('selectRow', index)
                            .datagrid('beginEdit', index);
                    editIndex = index;
                } else {
                    $('#dg8').datagrid('selectRow', editIndex);
                }
            }
        }

        function grid8Accept() {
            //              
            $('#dg8').datagrid('endEdit', editIndex);

            for (var i = 0; i < addRowsCount; i++)
            {
                $('#dg8').datagrid('endEdit', i);
            }
            if (grid8EndEditing()) {

                //           

                var rows = $('#dg8').datagrid('getChanges');
                var strArr = new Array();
                strArr[0] = "EMPID";
                strArr[1] = "NAME";
                strArr[2] = "GENDER";
                strArr[3] = "BIRTHDAY";
                strArr[4] = "DEPTNO";
                var employees = JSON.stringify(rows, strArr);

                if ($.trim(employees) != "[]") {
                    $.post('/Home/grid8SaveEditions', employees, function (res) {
                        var resObj = eval('(' + res + ')');
                        var resTxt = "   :" + resObj.addTotal + "     :" + resObj.addSuccessCount + "
:" + resObj.editTotal + " :" + resObj.editSuccessCount; alert(resTxt); }, 'text'); $('#dg8').datagrid('acceptChanges'); } else { alert(" , "); }; } }
controler:
 public string grid8GetData()
        {
            //  datagrid       :
            string sortName=Request.Form["sort"];
            string sortOrder=Request.Form["order"];
            int pageIndex = Convert.ToInt32(Request.Form["page"]);
            int pageSize = Convert.ToInt32(Request.Form["rows"]);
            //            :(      System.Globalization)
            DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy-mm-dd";
           List<OracleParameter> parmList =new List<OracleParameter> { 
                                          new  OracleParameter(":NAME","%"+Request.Form["name"]+"%"),
                                          //new  OracleParameter(":GENDER",Convert.ToInt16( Request.Form["gender"])),
                                          //new  OracleParameter(":DEPTNO",Convert.ToInt32( Request.Form["deptname"])),
                                          new  OracleParameter(":STIME",Convert.ToDateTime(Request.Form["stime"],dtFormat)),
                                          new  OracleParameter(":ETIME",Convert.ToDateTime(Request.Form["etime"],dtFormat))
                                      };
            StringBuilder sb= new StringBuilder(" ");
            if(Request.Form["gender"]!="-1")
            {
                parmList.Add(new OracleParameter(":GENDER", Convert.ToInt16(Request.Form["gender"])));
                sb.Append("and gender=:GENDER  ");
            }
            if (Request.Form["deptname"] != "-1")
            {
                parmList.Add( new OracleParameter(":DEPTNO", Convert.ToInt32(Request.Form["deptname"])));
                sb.Append("and deptno=:DEPTNO");
            }
            string where = sb.ToString();
            int total = 0;
            DataSet ds = grid8Service.GetEmployeesByPaging(where,sortName,sortOrder,pageSize,pageIndex,out total,parmList.ToArray() );
            //  hashtable   datagrid     
            Hashtable hs = new Hashtable();
            var formatter = new IsoDateTimeConverter();
            formatter.DateTimeFormat = "yyyy-MM-dd";
            hs.Add("total", total);
            hs.Add("rows", ds.Tables[0]);
            //     :
            return JsonConvert.SerializeObject(hs, formatter);
            //string jsonStr = JsonConvert.SerializeObject(ds.Tables[0],formatter); 
            //return jsonStr;
        }

        public ActionResult initCombobox8Data()
        {
            DataSet ds = grid8Service.GetAllDept();
            string jsonStr = JsonConvert.SerializeObject(ds.Tables[0]);
            return Json(jsonStr);
        }

        public string grid8SaveEditions()
        {
            //               :
            string data = Request.Form[0];
            data = data.Replace('[', ' ');
            data = data.Replace(']', ' ');


            string[] sss = { "}," };
            string[] ss = data.Split(sss, StringSplitOptions.None);
            int i = ss.Length;
            int lastStrLength = ss[i - 1].Length;
            ss[i - 1] = ss[i - 1].Remove(lastStrLength - 2, 1);
            List<Employee_wcj> emps = new List<Employee_wcj>();

            foreach (string s in ss)
            {

                string s1 = s + "}";
                Employee_wcj emp = JsonConvert.DeserializeObject<Employee_wcj>(s1);
                emps.Add(emp);
            }
            string res = grid8Service.grid8SaveEditions(emps);
            return res;
        }
サービス層:
 public  クラス WCJgrid 8
    {
        public DataSet GetAllDept()
        {
            ストリングス sql = プロジェクト * from departmentuw ";
            return OracleHelper.Query(sql);
        }
        public DataSet GetEmployees ByPaging(string) where ストリングス sortName、string sortOrder、 要点 PageSize、 要点 currentPage out 要点 レスルトンCount Oracle Parameeter[] parms)
        {
            String sql = @"プロジェクト * from employeew where NAME LIKE :NAME   and BIRTHDAY between :STIME  AND :ETIME"+where;
            //String sql = @プロジェクト emp.emppid、emp.name as empcame,emp.gender,emp.birthday,emp.deptno,dept.name dept[uname] from employeew AS emp ジョン employeew AS dept オン emp.deptno=dept.deptid where emp.NAME LIKE :NAME   and  emp.BIRTHDAY between :STIME  AND :ETIME" + where;
            StringBuider sortStr = new StringBuider()
            ストリングス order by = “”
            if (!string.IsNull OrEmpty(sortName)
            {
                if (sortName.Coontains(',')
                {
                    for (int i = 0; i < sortName.Split(',').Length; i++)
                    {
                        sortStr .Apple( sortName.Split(',')[i] + 「 " + sortOrder.Split(',')[i] + ",");
                    }
                    sortStr = sortStr.Remove(sortStr.Length-1,1)
                }
                else
                {
                    sortStr .Apple( sortName + " " + sortOrder
                }
                order by = sortStr.ToString()
            }
            else
            {
                order by = "";
            }
            return OracleHelper.FindPageBySql(sql) order by PageSize、 currentPage out レスルトンCount parms;
        }
        public ストリングス grid 8 SaveEditions List ems)
        {
            要点 edit Total = 0;
            要点 addTotal = 0;
            要点 edit Success Count = 0;
            要点 addSuccess Count = 0;
            foreach(Employeeuwcj emp in ems)
            {
                if (emp.EMPID != 88)
                {
                    edit Total += 1;
                    edit Success Count += grid 8 SaveUpdate(emp);
                }
                else
                {
                    addTotal += 1;
                    addSuccess Count += grid 8 SaveAdd(emp)
                }
            }
            return "{edit Total:” + editotal.ToString() + 「addTotal:」 + addTotal.ToString() + 「edit Success Count:」 + edit Success Count.ToString() + 「addSuccess Count:」 + addSuccess Count.ToString() + 「③」
        }
        public 要点 grid 8 SaveUpdate(Employeeuwcj emp)
        {
           
            //ストリングス sql = 「udate employeew セット 
name=「+emp.NAME+」、gender=「+emp.GENDER+」、birthday=「+emp.BIRTHDAY+」、deptno=「+emp.DEPTNO.ToStering()+」 where emppid=「+emp.EMPID.ToString()+」
            //要点 ローソン = OracleHelper.ExecuteNonQuery(sql,CommandType.Text)
            ストリングス sql = 「udate employeew セット name=:name ,gender=:gender bithday=:bithday,deptno=:deptno where emppid=:emppid";
            DateTimeFormatInfo dt Format = new System.Globalization.DateTimeFormatInfo()
            dt Format.Shot DatePattern = 「yyy-M-dd」
            Oracle Parameeter[] パラ = { 
                                         new OracleParameeter(「name」、emp.NAME)、
                                         new  Oracle Parameeter(「:gender」、int.Parse(emp.GENDER))、
                                         new  Oracle Parameeter(「:birthday」、 Covert.ToDateTime(emp.BIRTHDAY,dt Format) )),
                                         new  OracleParameeter(「:deptno」、Covert.ToInt 32(emp.DEPTNO)、
                                         new  OracleParameeter(「:emppid」、Covert.ToInt 32(emp.EMPID)
                                     };
            要点 ローソン = OracleHelper.ExecuteNonQuery(sql, CommandType.Text、 パラ)
            return ローソン
        }
        public 要点 grid 8 SaveAdd(Employeeuwcj) emp)
        {
             //パラメータ配列とtodate()メソッドを組み合わせて使うsql文
            //ストリングス sql = “insert” イント employeew values(「+emp.EMPID.ToString()+」、「+emp.NAME+」、「+emp.GENDER.ToString()+」、toudte('「+emp.BIRTHDAY+」、'、''yyy-mm-dd')、「+emp.DEPTNO.Toring+」
            //要点 ローソン = OracleHelper.ExecuteNonQuery(sql,CommandType.Text)
            ストリングス sql = “insert” イント employeew values(:emppid,:name,:gender,toudte(:birthday,'yyy-mm-dd'),:deptno)";
            DateTimeFormatInfo dt Format = new System.Globalization.DateTimeFormatInfo()
            dt Format.Shot DatePattern = 「yyy-M-dd」
            Oracle Parameeter[] パラ = { 
                                         new OracleParameeter(「name」、emp.NAME)、
                                         new  Oracle Parameeter(「:gender」、int.Parse(emp.GENDER))、
                                         new  Oracle Parameeter(「:birthday」、 Covert.ToDateTime(emp.BIRTHDAY,dt Format) )),
                                         new  OracleParameeter(「:deptno」、Covert.ToInt 32(emp.DEPTNO)、
                                         new  OracleParameeter(「:emppid」、Covert.ToInt 32(emp.EMPID)
                                     };
            要点 ローソン = OracleHelper.ExecuteNonQuery(sql, CommandType.Text、 パラ)
            return ローソン
        }
    }
記事のソース:
http://blog.csdn.net/wcj920946195