欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Easyui datagrid绑定数据,新增,修改,删除方法(一)

程序员文章站 2022-05-25 16:26:08
@{ ViewBag.Title = "UsersList"; } @{ Html.RenderAction("SearchRole", "Shared"); } 账号(编号或姓名): ... ......
@{
    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>