EasyUI表格删除多个表的多条数据

1.页面代码:通过datagrid的勾选框选中多条数据,用逗号拼接ID,  并以post方式传给后台控制器

 //删除用户(可批量)
        function DelUser() {
            var rows = $("#ui_user_dg").datagrid("getChecked");
            if (rows.length < 1) {
                $.show_alert("提示", "请先勾选要删除的用户");
                return;
            }
            $.messager.confirm('提示', '确定删除选中行吗?', function (r) {
                if (r) {
                    var parmIds = "";
                    $.each(rows, function (i, row) {
                        parmIds += row.ID + ",";
                    });
                    parmIds = parmIds.substring(0, parmIds.length - 1);
                    $.ajax({
                        url: "/User/DelUserByIDs",
                        data: {
                            IDs: parmIds
                        },
                        type: "POST",
                        dataType: "json",
                        success: function (data) {
                            if (data.success) {
                                $.show_alert("提示", data.msg);
                                $("#ui_user_dg").datagrid("reload").datagrid('clearSelections').datagrid('clearChecked');
                            } else {
                                $.show_alert("提示", data.msg);
                            }
                        }
                    });
                }
            });
        }

 

2.控制器接收页面传来的数据Ids,通过调用删除的BLL方法,

new UserBLL().DeleteUser(Ids)
  public ActionResult DelUserByIDs()
        {
            try
            {
                string Ids = Request["IDs"] == null ? "" : Request["IDs"];
                if (!string.IsNullOrEmpty(Ids))
                {
                    if (new UserBLL().DeleteUser(Ids))
                    {
                        return Content("{\"msg\":\"删除成功!\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"删除失败!\",\"success\":false}");
                    }
                }
                else
                {
                    return Content("{\"msg\":\"删除失败!\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
            }
        }

 

3.BLL方法(起到在控制器与DAL之间传递参数的作用)

 /// <summary>
        /// 删除用户(可批量删除,删除用户同时删除对应的权限和所处的部门)
        /// </summary>
        public bool DeleteUser(string idList)
        {
            return dal.DeleteUser(idList);
        }

 

4.DAL方法()

List<string> list = new List<string>();
            list.Add("delete from tbUser where ID in (" + idList + ")");
            list.Add("delete from tbUserRole where UserId in (" + idList + ")");
通过泛型对象执行两条sql语句实现删除多个表的作用,in关键字是为了删除多个Ids的数据
/// <summary>
        /// 删除用户(可批量删除,删除用户同时删除对应的权限和所处的部门)
        /// </summary>
        /// idList是以逗号拼接起来的一个字符串
        public bool DeleteUser(string idList)
        {
            List<string> list = new List<string>();
            list.Add("delete from tbUser where ID in (" + idList + ")");
            list.Add("delete from tbUserRole where UserId in (" + idList + ")");

            try
            {
                int count = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, list);
                if (count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

 

 

5.SqlHelper帮助类

 /// <summary>
        /// 执行多条sql语句(List泛型集合)【事务】(无参数)
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="listSql">包含多条sql语句的泛型集合</param>
        /// <returns>受影响行数</returns>
        public static int ExecuteNonQuery(string connectionString, List<string> listSql)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            SqlTransaction trans = conn.BeginTransaction();
            PrepareCommand(cmd, conn, trans, CommandType.Text, null, null);
            try
            {
                int count = 0;
                for (int n = 0; n < listSql.Count; n++)
                {
                    string strSql = listSql[n];
                    if (strSql.Trim().Length > 1)
                    {
                        cmd.CommandText = strSql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                trans.Commit();
                cmd.Parameters.Clear();
                return count;
            }
            catch
            {
                trans.Rollback();
                cmd.Parameters.Clear();
                return 0;
            }
            finally
            {
                conn.Close();
            }
        }

/// <summary>
/// 准备一个待执行的SqlCommand
/// </summary>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, params SqlParameter[] paras)
{
try
{
if (conn.State != ConnectionState.Open)
{
conn.Close();
conn.Open();
}
cmd.Connection = conn;
if (commandText != null)
cmd.CommandText = commandText;
cmd.CommandType = commandType; //这里设置执行的是T-Sql语句还是存储过程


if (trans != null)
cmd.Transaction = trans;


if (paras != null && paras.Length > 0)
{
//cmd.Parameters.AddRange(paras);
for (int i = 0; i < paras.Length; i++)
{
if (paras[i].Value == null || paras[i].Value.ToString() == "")
paras[i].Value = DBNull.Value; //插入或修改时,如果有参数是空字符串,那么以NULL的形式插入数据库
cmd.Parameters.Add(paras[i]);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

 

 

想要项目源码的小伙伴可以加我qq:3539447520@qq.com,请先备注交好友原因,否则不通过哦

 

posted @ 2019-08-06 14:41  风葬秋暝  阅读(360)  评论(0编辑  收藏  举报