Mvc+三层(批量添加、删除、修改)

DAL层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using System.Data;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace DAL
{
    
    public class StuDal
    {
        public static SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Day15;Integrated Security=True");
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public List<Student> GetStu(string name)
        {
            string sql = "select * from Student where 1=1";
            if (!string.IsNullOrEmpty(name))
            {
                sql += "and StuName like ‘%"+name+"%‘";
            }
            var res=DBHelper.GetDataSet(sql).Tables[0];
            var resd=JsonConvert.SerializeObject(res);
            var list=JsonConvert.DeserializeObject<List<Student>>(resd);
            return list;
        }

/// <summary>
        /// 添加
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public int AddStu(Student s)
        {
            string sql = string.Format("insert into Student values(‘{0}‘,‘{1}‘,{2})",s.StuNum,s.StuName,s.Age);
            return DBHelper.ExecuteNonQuery(sql);
        }

/// <summary>
        /// 事务添加
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public int AddList(List<Student> list)
        {
            conn.Open();
            using (SqlTransaction tran=conn.BeginTransaction())
            {
                try
                {
                    int res=0;
                    foreach (var item in list)
                    {
                        string sql = string.Format("insert into Student values(‘{0}‘,‘{1}‘,{2})",item.StuNum,item.StuName,item.Age);
                        SqlCommand command = new SqlCommand(sql, conn);
                        command.Transaction = tran;
                        int result = command.ExecuteNonQuery();
                        res += result;
                    }
                    tran.Commit();
                    conn.Close();
                    return res;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    conn.Close();
                    return 0;
                }
            }
        }

/// <summary>
        /// 删除
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public int DelStu(string  id)
        {
            string sql = "delete Student where Id in ‘" + id + "‘";
            return DBHelper.ExecuteNonQuery(sql);
        }

/// <summary>
        /// 存储过程删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Del(int id)
        {
            conn.Open();
            SqlCommand com = new SqlCommand("P_Shanchu",conn);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@id", SqlDbType.Int).Value = id;

com.Parameters.AddWithValue("@return_value", SqlDbType.Int);
            com.Parameters["@return_value"].Direction = ParameterDirection.ReturnValue;
            //执行
            com.ExecuteNonQuery();
            conn.Close();
            return Convert.ToInt32(com.Parameters["@return_value"].Direction);

// return Convert.ToInt32(com.Parameters.AddWithValue("@return_value", SqlDbType.Int).Value);
            
        }

/// <summary>
        /// 修改
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public int UpdStu(Student s)
        {
            string sql =string.Format("update Student set StuNum=‘{0}‘,StuName=‘{1}‘,Age={2} where ID={3}", s.StuNum, s.StuName, s.Age,s.ID);
            return DBHelper.ExecuteNonQuery(sql);
        }

/// <summary>
        /// 查询单条数据
        /// </summary>
        /// <returns></returns>
        public List<Student> GetStuByID(int id)
        {
            string sql = "select * from Student where ID="+id;
            var res = DBHelper.GetDataSet(sql).Tables[0];
            var resd = JsonConvert.SerializeObject(res);
            var list = JsonConvert.DeserializeObject<List<Student>>(resd);
            return list;
        }
    }
}

controller层

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using Model;
using Newtonsoft.Json;

namespace Day15Mvc.Controllers
{
    public class StuController : Controller
    {
        //
        // GET: /Stu/

//对象实例化
        StuBll bll = new StuBll();

public ActionResult Index()
        {
         
            return View();
        }
        
        public ActionResult Show()
        {
            return View();
            
        }
        [HttpPost]
        public JsonResult DelShow(int id)
        {
            int q = bll.Del(id);
            if (q > 0)
            {
                return Json(new { code = 1, message = "成功" });
            }
            else
            {
                return Json(new { code = 0, message = "失败" });
            }

}

[HttpPost]
        public JsonResult ShowStu(string name)
        {
            var res = bll.GetStu(name);         
            return Json(res);
        }
        
        public JsonResult AddStu(string str)
        {
            str= str.TrimEnd(‘|‘);
            string[] st = str.Split(‘|‘);
            //判断是否有值
            if (st == null || st.Length == 0)
            {
                //匿名类
                return Json(new { code = 0, message = "失败" });
            }
            else
            {
                List<Student> list = new List<Student>();
                foreach (var item in st)
                {
                    string[] s = item.Split(‘,‘);
                    if (s == null || s.Length == 0)
                    {
                        break;
                       // return Json(new { code = 0, message = "失败" });                      
                    }
                    else
                    {
                        Student student = new Student();
                        student.StuNum = s[0];
                        student.StuName = s[1];
                        student.Age = Convert.ToInt32(s[2]);
                        list.Add(student);                     
                    }
                }

if (bll.AddList(list) > 0)
                {
                    return Json(new { code = 1, message = "添加成功" });
                }
                else
                {
                    return Json(new { code = 0, message = "添加失败" });
                }
            }
           
            
        }

[HttpPost]
        public JsonResult UpdStu(string id,string num,string name,string age)
        {
            Student stu = new Student()
            {
                ID = Convert.ToInt32(id),
                StuNum = num,
                StuName = name,
                Age = Convert.ToInt32(age)
            };

if (bll.UpdStu(stu) > 0)
            {
                return Json(new { code = 1, message = "修改成功" });
            }
            else
            {
                return Json(new { code = 0, message = "修改失败" });
            }
        }
    }
}

前台

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Show</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script>
        
        //显示数据
        function show()
        {
            var name = $("#txtName").val();
            $.ajax({
                url: "/Stu/ShowStu",
                type: "Post",
                dataType: "json",
                data:{name:name},
                success: function (data) {
                    $("#tbody1").html("");
                    for (var i = 0; i < data.length; i++) {
                        $("#tbody1").append("<tr>"
                            + "<td>" + data[i].ID + "</td>"
                            + "<td>" + data[i].StuNum + "</td>"
                            + "<td>" + data[i].StuName + "</td>"
                            + "<td>" + data[i].Age + "</td>"
                            + "<td><input  class=\"btnDel\" type=\"button\" value=\"删除\" onclick=‘dell(" + data[i].ID + ")‘ /><input  class=\"btnUpd\" type=\"button\" value=\"修改\"/></td>"
                            + "</tr>")
                    }
                }
            });
        }
        //文档就绪函数
        $(function () {
            show();
            //添加一行
            $("#btnAdd").click(function () {
                $("#tbody1").append("<tr class=‘Addtr‘>"
                        + "<td></td>"
                        + "<td><input name=\"Text2\" type=\"text\" /></td>"
                        + "<td><input name=\"Text3\" type=\"text\" /></td>"
                        + "<td><input name=\"Text4\" type=\"text\" /></td>"
                        + "<td><input class=\"btnDel\" type=\"button\" value=\"删除\" /></td>"
                        + "</tr>")
            })
            //添加数据
            $("#btnSal").click(function () {
                var res = "";
                $(".Addtr").each(function () {
                    var num = $(this).find("input[name=‘Text2‘]").val();
                    var name = $(this).find("input[name=‘Text3‘]").val();
                    var age = $(this).find("input[name=‘Text4‘]").val();
                    res += num + "," + name + "," + age + "|";
                })
                $.ajax({
                    url: "/Stu/AddStu",
                    type: "post",
                    dataType: "json",
                    data: { str: res },
                    success: function (Data)
                    {
                        if (Data.code == 1) {
                            alert(Data.message);
                            show();
                        }
                        else {
                            alert(Data.message);
                        }
                    }
                })
            })

//修改的数据
            $(document).on("click", ".btnUpd", function () {
                if ($(this).val() == "修改") {
                    var id = $(this).parent().siblings().eq(0).html();
                    var num = $(this).parent().siblings().eq(1).html();
                    var name = $(this).parent().siblings().eq(2).html();
                    var age = $(this).parent().siblings().eq(3).html();

$(this).parent().siblings().eq(1).html("<input name=\"Text2\" type=\"text\" value=‘" + num + "‘/>");
                    $(this).parent().siblings().eq(2).html("<input name=\"Text3\" type=\"text\" value=‘" + name + "‘/>");
                    $(this).parent().siblings().eq(3).html("<input name=\"Text4\" type=\"text\" value=‘" + age + "‘/>");
                    $(this).val("确定");
                }
                else {
                    
                        var id = $(this).parent().siblings().eq(0).html();
                        var num = $(this).parent().parent().find("input[name=‘Text2‘]").val();
                        var name = $(this).parent().parent().find("input[name=‘Text3‘]").val();
                        var age = $(this).parent().parent().find("input[name=‘Text4‘]").val();

$.ajax({
                            url: "/Stu/UpdStu",
                            type: "post",
                            dataType: "json",
                            data: { id: id,num:num,name:name,age:age },
                            success: function (Data) {
                                if (Data.code == 1) {
                                    alert(Data.message);
                                    show();
                                }
                                else {
                                    alert(Data.message);
                                }
                            }
                        })
                    
                }
            })

//$(".btndel").parent().siblings().eq(0).text();
        })

//删除
        function dell(id)
        {
            $.ajax({
                url: "/Stu/DelShow",
                type: "post",
                dataType: "json",
                data: { id: id },
                success: function (Data) {
                    if (Data.code == 1) {
                        alert(Data.message);
                        show();
                    }
                    else {
                        alert(Data.message);
                    }
                }
            })
        }

</script>
</head>
<body>
    <div>
        <input id="txtName" type="text" />
        <input id="Button1" type="button" value="查询" onclick="show()"/>
        <input id="btnAdd" type="button" value="添加" />
        <input id="btnSal" type="button" value="保存" />
        <table class="table table-bordered">
            <thead>
                <tr>
                    <td>编号</td>
                    <td>学号</td>
                    <td>姓名</td>
                    <td>年龄</td>
                    <td>操作</td>
                </tr>
            </thead>
            <tbody id="tbody1"></tbody>
        </table>
    </div>
</body>
</html>

原文地址:https://www.cnblogs.com/lhn5xy/p/8379311.html

时间: 2024-11-08 23:41:35

Mvc+三层(批量添加、删除、修改)的相关文章

myBatis批量添加,修改和删除

摘自: http://blog.csdn.net/myjlvzlp/article/details/8434376 1.批量添加元素session.insert(String string,Object o) public void batchInsertStudent(){ List<Student> ls = new ArrayList<Student>(); for(int i = 5;i < 8;i++){ Student student = new Student(

IIS环境下如何批量添加、修改、删除绑定的域名

IIS环境下如何批量添加和修改所绑定域名 1.关闭IISADMIN服务和W3SVC服务,可以从服务里面关闭,也可以直接执行命令:net stop iisadmin /y: 2.打开“C:\WINDOWS\SYSTEM32\INETSVR”,找到Metabase.xml,这就是存放iis信息的地方了,包括IIS的配置及网站配置都在这个文件中,备份一下,防止出错: 3.找到要修改的站点,根据原来的形式添加域名绑定,保存Metabase.xml: 4.重启IIS,可直接使用IISRESET来实现: 5

JTree 添加 , 删除, 修改

package com.swing.demo; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.CellEdi

&lt;linux小脚本&gt;批量添加/删除用户

批量添加/删除用户,当输入add时,判断用户是否存在,存在则显示存在,不存在则添加:当输入del时,判断用户是否存在,存在则删除用户,不存在则显示不存在. #!/bin/bash if [ $1 == "add" ];then for i in {1..10}; do if id user$i &> /dev/null;then echo "the user$i exists!" else useradd user$i &> /dev/n

用SQL语句添加删除修改字段

1.增加字段     alter table docdsp     add dspcodechar(200)2.删除字段     ALTER TABLE table_NAME DROP COLUMNcolumn_NAME3.修改字段类型     ALTER TABLE table_name     ALTER COLUMNcolumn_name new_data_type4.sp_rename 改名     EXEC sp_rename '[dbo].[Table_1].[filedName1]

用SQL语句添加删除修改字段、一些表与字段的基本操作、数据库备份等

用SQL语句添加删除修改字段 1.增加字段 alter table docdsp add dspcode char(200) 2.删除字段 ALTER TABLE table_NAME DROP COLUMN column_NAME 3.修改字段类型 ALTER TABLE table_name ALTER COLUMN column_name new_data_type 4.sp_rename 改名 更改当前数据库中用户创建对象(如表.列或用户定义数据类型)的名称. 语法 sp_rename

对表格单元格的添加删除修改

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

EF6基础系列(12)--- EF进行批量添加/删除

EF6添加了批量添加/删除实体集合的方法,我们可以使用DbSet.AddRange()方法将实体集合添加到上下文,同时实体集合中的每一个实体的状态都标记为Added,在执行SaveChange()方法时为每个实体执行Insert操作:同样的我们使用DbSet.RemoveRange()方法将集合中的所有实体都标记为deleted状态,在执行SaveChange()方法时为每一条数据执行delete操作. 通过AddRange()和RemoveRange()方法可以有效提升性能,所以建议在进行不批

JavaScript学习 - 基础(八) - DOM 节点 添加/删除/修改/属性值操作

html代码: <!--添加/删除/修改 --> <div id="a1"> <button id="a2" onclick="add()">add</button> </div> <div id="a3"> <button onclick="del()">del</button> </div> &l

批量添加删除用户

批量添加用户 #!/bin/bash read -p "Enter the User Password : " PASSWD for UNAME in `cat users.txt` do id $UNAME &> /dev/null if [ $? -eq 0 ];then echo "Already exists" else useradd $UNAME &> /dev/null echo "$PASSWD" |