1. 程式人生 > >基於Easyui框架的datagrid繫結資料,新增,修改,刪除方法(一)

基於Easyui框架的datagrid繫結資料,新增,修改,刪除方法(一)

基於Easyui框架的datagrid繫結資料,新增,修改,刪除方法
第一種:https://blog.csdn.net/u012949335/article/details/81943387
第二種:https://blog.csdn.net/u012949335/article/details/81910663
第三種:https://blog.csdn.net/u012949335/article/details/81777842
第四種:https://blog.csdn.net/u012949335/article/details/81777744 

@{
    ViewBag.Title = "UsersList";
}


<script type="text/javascript">

   $(function(){
      BindData();
   })
    //當請求遠端資料時,傳送的額外引數。
    function GetqueryParams() {
        var Params = {};
        Params.SearchRole = $("#SearchRole").combobox('getValue');
        Params.Jzzhch = $("#txtUserZhxm").textbox('getValue');
        return Params;
    }

    function UserinfoSearch()
    {
        $("#dg").datagrid("reload",GetqueryParams());
    }
    //刪除
    function User_Del() {
        var rows = $('#dg').datagrid("getSelections");
        if (rows.length > 0) {
            $.messager.confirm("提示", "你確定要刪除嗎?", function (r) {
                if (r) {
                    var ids = [];
                    for (var i = 0; i < rows.length; i++) {
                       ids.push(rows[i].userid);
                    }
                    var jsonObject = JSON.stringify(ids);
                    DelRows(jsonObject);
                }
            });
        }
        else {
            $.messager.alert("提示", "請選擇要刪除的行", "error");
        }
    }

     function DelRows(userids) {
        $.ajax({
            type: 'post',
            dataType: "json", //返回json格式的資料
            url: "UsersList_Del",
            data: { 'UsersJson': userids },
            cache: false,
            success: function (Data) {
                if (Data == "1") {
                    $('#dg').datagrid("reload");
                    $.messager.alert("提示", "刪除成功");
                }
                else {
                    $.messager.alert("提示", "刪除失敗", "error");
                }
            },
            error: function (e) {
                var msg = responseTextTitle(e.responseText);
                $.messager.alert("提示", msg, "error");
            }
        });
    }

    function getRowIndex(target) {
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }

     function EidtUserForm(target) {
        var title="編輯";
        if (target) {
            var thisindex = getRowIndex(target);
            var row = $('#dg').datagrid('getRows')[thisindex];
            $('#txtuserid').textbox('readonly',true);
            $('#txtuserzh').textbox('readonly',true);
            $('#txtuserid').textbox("setValue",row.userid);
            $('#txtuserzh').textbox('setValue',row.userzh);
            $('#password1').textbox("setValue","");
            $('#password2').textbox("setValue","");
            $('#txtusername').textbox("setValue", row.username);
            $('#userrole').combobox('setValues', row.role);
            $("input[name='status'][value=" + row.status + "]").prop("checked", true);
            $('#dg').datagrid('clearSelections');
        }
        else {
            $('#txtuserid').textbox('readonly',true);
            $('#txtuserzh').textbox('setValue',"");
            $('#txtuserzh').textbox('readonly',false);
            $('#txtuserid').textbox("setValue","");
            $('#password1').textbox("setValue","");
            $('#password2').textbox("setValue","");
            $('#txtusername').textbox("setValue", "");
            $('#userrole').combobox('setValues', "");
            $("input[name='status'][value='1']").prop("checked", true);
            title="新增";
        }
        $('#window_userinfo').window({
            width: 500,
            title: title,
            modal: true
        });
        $('#window_userinfo').window('open');
        $('#window_userinfo').window('vcenter');
        $('#window_userinfo').window('hcenter');
     }

     function SaveUserInfo()
     {
        var isValid = $("#yzxx").form('enableValidation').form('validate');
        if (!isValid) {
            $.messager.progress('close'); // hide progress bar while the form is invalid
            return isValid;
        }
         if($('#password1').textbox("getValue")!=$('#password2').textbox("getValue"))
         {
            $.messager.alert("提示", "兩次密碼輸入不一樣", "");
            return false;
         }
         if($('#userrole').combobox("getValues")=="")
         {
            $.messager.alert("提示", "請選擇角色", "");
            return false;
         }
          //var userinfo = $('#yzxx').serializeObject();
          var userinfo = new Object();
          userinfo.userid=$('#txtuserid').textbox("getValue");
          userinfo.userzh=$('#txtuserzh').textbox("getValue");
          userinfo.username=$('#txtusername').textbox("getValue");
          userinfo.passwd=$('#password1').textbox("getValue");
          userinfo.role=$('#userrole').combobox('getValue');
          userinfo.status=$("input[name='status']:checked").val();
          var jsonObject = JSON.stringify(userinfo);
          $.ajax({
            type: 'post',
            dataType: "json",
            url: "@Url.Content("~/Home/UsersList_UsersInfoAddEdit")",
            data: { 'json': jsonObject },
            cache: false,
            success: function (data) {
                if (data == "1") {
                    $.messager.alert("提示", "儲存成功", "");
                    $('#dg').datagrid("reload");
                    $('#window_userinfo').window('close');
                }
                else {
                    $.messager.alert("提示", data.msg, "error");
                }
            },
            error: function (e) {
                $.messager.alert("提示", "儲存失敗" + e.toString(), "error");
            }
         });
     }

    function BindData() {
        var queryParams = GetqueryParams();
        $('#dg').datagrid({
            width: 'auto',
            height: 'auto',
            scrollbarSize: 0,
            autoRowHeight: false,
            url: "@Url.Content("~/Home/UsersList_BindSearch")",
            queryParams: queryParams,
            checkOnSelect:false,
            selectOnCheck:true,
            idField: 'userid',
            columns: [[
                { field: 'ck', title: '選擇', sortable: true, checkbox: true },
                { field: 'userid', title: '編號', width: "10%", sortable: true },
                { field: 'userzh', title: '使用者賬號', width: "10%", sortable: true },
                { field: 'username', title: '姓名', width: "20%", sortable: true},
                { field: 'status', title: '狀態', width: "20%", sortable: true,formatter:function(value, row, index){
                    return row.zt;
                }  },
                { field: 'role', title: '角色', width: "20%", sortable: true ,formatter:function(value, row, index){
                    return row.dmmc;
                }  },
                { field: 'action', title: '操作', width: "15%", align: 'center',
                    formatter: function (value, row, index) {
                        var e = '<a class="but-link" href="javascript:void(0)" onclick="EidtUserForm(this)"><span class="icon icon-edit"></span>編輯</a> ';
                        return e;
                    }
                }
            ]],
            onLoadSuccess: function(data){//載入完畢後獲取所有的checkbox遍歷
            if (data.rows.length > 0) {
                //迴圈判斷操作為新增的不能選擇
                for (var i = 0; i < data.rows.length; i++) {
                    //根據userid讓某些行不可選
                    if (data.rows[i].userid == "system") {
                        $("input[type='checkbox']")[i + 1].disabled = true;//禁用
                        //$("input[type='checkbox']")[i + 1].remove();//移除
                    }
                }
                //$(".datagrid-header-check").html("");
              }else
              {
                    $(".div_empty").css({ "display": "block" });
                    $(this).closest('div.datagrid-wrap').find('div.datagrid-pager').hide();
              }

            },
            //當用戶勾選全部行時觸發
            onCheckAll : function(rows) {  
                $("input[type='checkbox']").each(function(index, el) {
                    if(el.disabled== true){
                        $("#dg").datagrid('uncheckRow', index-1);//此處參考其他人的程式碼,原始碼為unselectRow 
                    }
                    var checkboxHeader = $('div.datagrid-header-check input[type=checkbox]');//取到全選全不選這個元素
                    checkboxHeader.prop("checked","checked");//將其設定為checked即可
                });
           },
            onClickRow: function(rowIndex, rowData){
               //載入完畢後獲取所有的checkbox遍歷
                $("input[type='checkbox']").each(function(index, el){
                    //如果當前的複選框不可選,則不讓其選中
                    if (el.disabled == true) {
                        //POSStockHeadTable.datagrid('unselectRow', index - 1);
                      }
                })
            },
            pageSize: 10,
            pageList: [10, 20, 30, 50],
            fitColumns: true,
            striped: true,
            pagination: true, //分頁控制元件 
            rownumbers: true, //行號
            onLoadError: function (e) {
                $.messager.alert("提示", "載入失敗", "error");
            }
        });
    
     }

</script>


<div class="tools-row">
    <table width="100%" id="table" style="padding-left:8px; border-spacing:0px; border-collapse:separate;">
        <tr>
            <td style="height:28px;" colspan="2">
            @{
                Html.RenderAction("SearchRole", "Shared");
                    }
                賬號(編號或姓名):<input class="easyui-textbox" id="txtUserZhxm" data-options="width:80"/>
                &nbsp; &nbsp; <button id="btnsearch" type="button" class="but-default" onclick="UserinfoSearch()"><span class="icon icon-magnifier"></span> 查詢</button>
            </td>
        </tr>
    </table>
</div>
<div class="tools-row">
    <table cellpadding="0" cellspacing="0" style="width:100%">
        <tr>
            <td align="right">
            <button id="btnadd" type="button" class="but-primary" onclick="EidtUserForm()"><span class="icon icon-add"></span>新增</button>&nbsp;&nbsp;
            <button id="btndel" type="button" class="but-primary" onclick="User_Del()"><span class="icon icon-delete"></span>刪除</button>
            
            </td>
        </tr>
    </table>
</div>
<table id="dg"></table>
<div class="div_empty" style="height: 150px; display:none; border-top: 0px solid; background-color:White;">
      <div style="width: 95%; text-align: center; border: 0px; margin-top: 5%; font-size:20px; font-family: 宋體;position: absolute">
          暫無資料!
       </div>
 </div>

<div id="window_userinfo" class="easyui-window" title="修改密碼" data-options="modal:true,closed:true,region:'center'">
<form id="yzxx" method="post">
    <table cellpadding="5" class="basetable">
        <tr>
            <td>
                編號(自動生成):
            </td>
            <td>
                <input class="easyui-textbox" id="txtuserid" placeholder="自動生成" type="text" name="username"></input>
            </td>
        </tr>
        <tr>
            <td>
                使用者賬號:
            </td>
            <td>
                <input class="easyui-textbox" id="txtuserzh" type="text" name="username" data-options="required:true"></input>
            </td>
        </tr>
        <tr>
            <td>
                姓名:
            </td>
            <td>
                <input class="easyui-textbox" id="txtusername" type="text" name="username" data-options="required:true"></input>
            </td>
        </tr>

        <tr>
            <td>
                密碼:
            </td>
            <td>
                <input id="password1" class="easyui-textbox" type="password" data-options="required:true,validType:'length[6,50]'" />
            </td>
        </tr>
        <tr>
            <td>
                確認密碼:
            </td>
            <td>
                <input id="password2" class="easyui-textbox" type="password" data-options="required:true,validType:'length[6,50]'" />
            </td>
        </tr>

        <tr>
            <td>
                角色:
            </td>
            <td>
            @model YidiTutor.Models.comboboxModel_Json

                 <input id="userrole" class="easyui-combobox" name="userrole" style="width:80px;" data-options="data:@Model.data,
					            method:'get',
                                editable:false,
					            valueField:'dm',
					            textField:'dmmc',
					            panelHeight:'auto'"/>
            </td>
        </tr>
        <tr>
            <td>
                使用者狀態:
            </td>
            <td colspan="3">
                <input id="stauts1" type="radio" name="status" value="1" /><label for="stauts0">啟用</label>
                <input id="stauts0" type="radio" name="status" value="0" /><label for="stauts1">禁用</label>
            </td>
        </tr>
        <tr>
            <td colspan="4" align="right">
                <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save'" style="width: 80px"
        onclick="SaveUserInfo()">儲存</a> <a href="javascript:void(0)" class="easyui-linkbutton"
            data-options="iconCls:'icon-cancel'" onclick="$('#window_userinfo').window('close')" style="width: 80px">
            取消</a>
            </td>
        </tr>
    </table>
</form>
</div>