MVC增删改查整套(ajax,本页面,批量增)

///页面
<div>
        @using (Html.BeginForm())
        {
            <input id="txtname" type="text" /><input id="Button1" type="button" value="查询" onclick="Select()" class="btn btn-primary"/>
            <input type="button" id="AddBtn" value="添加 " class="btn btn-primary" />
            <input type="button" id="BaoCunBtn" value="保存 " class="btn btn-primary"/>
            <table id="table1" class="table table-bordered">
                <thead>
                    <tr>
                        <td>编号</td>
                        <td>学号</td>
                        <td>姓名</td>
                        <td>年龄</td>
                        <td>操作</td>
                    </tr>
                </thead>
                <tbody id="tbody1"></tbody>
            </table>
        }        
</div>

///ajax请求
<script>
        //显示方法
        function ShowList() {
            $.ajax({
                url: "/Student/StudentList",
                type: "post",
                success: function (data) {
                    $("#tbody1").html(" ");
                    var str = "";
                    for (var i = 0; i < data.length; i++) {
                        str += "<tr>"
                        str += "<td>" + data[i].ID + "</td>"
                        str += "<td>" + data[i].XueHao + "</td>"
                        str += "<td>" + data[i].StuName + "</td>"
                        str += "<td>" + data[i].Age + "</td>"
                        str += "<td><input  type=\"button\" value=\"删除存储过程\" onclick=\"DeleteCCGC(" + data[i].ID + ")\"  class=\"btn btn-primary\"/>"
                        str += "<input type=\"button\" value=\"删除\" onclick=\"Delete(" + data[i].ID + ")\"  class=\"btn btn-primary\"/>"
                        str += "<input type=\"button\" class=\"Update\" value=\"修改\" class=\"btn btn-primary\" />"
                        str += "<input type=\"button\" class=\"BaoCun\" value=\"保存\" style=\"display:none;\"  class=\"btn btn-primary\" />";
                        str += "<input type=\"button\" class=\"QuXiao\" value=\"取消\" style=\"display:none;\"  class=\"btn btn-primary\" /></td>";
                        str += "</tr>";
                    }
                    $("#tbody1").append(str);
                }
            })
        }

//删除
        function Delete(id) {
            $.ajax({
                url: "/Student/Delete?id=" + id,
                type: "post",
                success: function (data) {
                    if (data.code == 1) {
                        alert(data.msg);
                        ShowList();
                    }
                    else {
                        alert(data.msg);
                    }
                }
            })
        }

//删除存储过程
        function DeleteCCGC(id) {
                $.ajax({
                    url: "/Student/DeleteCCGC?id="+id,
                    type: "post",
                    success: function (data) {
                        if (data.code == 1) {
                            alert("删除成功!");
                            ShowList();
                        }
                        else {
                            alert("删除成功!");
                        }
                    }
                })
        }

//查询方法
        function Select() {
            var name=$("#txtname").val();
            $.ajax({
                url: "/Student/Select?name="+name,
                type: "post",
                success: function (data) {
                    $("#tbody1").html(" ");
                    var str = "";
                    for (var i = 0; i < data.length; i++) {
                        str += "<tr>"
                        str += "<td>" + data[i].ID + "</td>"
                        str += "<td>" + data[i].XueHao + "</td>"
                        str += "<td>" + data[i].StuName + "</td>"
                        str += "<td>" + data[i].Age + "</td>"
                        str += "<td><input  type=\"button\" value=\"删除存储过程\" onclick=\"DeleteCCGC(" + data[i].ID + ")\"  class=\"btn btn-primary\"/>"
                        str += "<input type=\"button\" value=\"删除\" onclick=\"Delete(" + data[i].ID + ")\"  class=\"btn btn-primary\"/>"
                        str += "<input type=\"button\" class=\"Update\" value=\"修改\" class=\"btn btn-primary\" />"
                        str += "<input type=\"button\" class=\"BaoCun\" value=\"保存\" style=\"display:none;\"  class=\"btn btn-primary\" />";
                        str += "<input type=\"button\" class=\"QuXiao\" value=\"取消\" style=\"display:none;\"  class=\"btn btn-primary\" /></td>";
                        str += "</tr>";
                    }
                    $("#tbody1").append(str);
                }
            })
        }

$(function () {
            //显示
            ShowList();
            
            //追加行方法1
            $("#AddBtn").click(function () {
                var HtmlStr = "";
                HtmlStr += "<tr class=\"AddTr\">"
                HtmlStr += "<td></td>"
                HtmlStr += "<td><input class=\"\" type=\"text\" /></td>"
                HtmlStr += "<td><input class=\"txtName\" type=\"text\" /></td>"
                HtmlStr += "<td><input class=\"txtAge\" type=\"text\" /></td>"
                HtmlStr += "<td></td>"
                HtmlStr += "</tr>"
                $("#tbody1").append(HtmlStr)
            })
            //追加行方法2
            //$("#AddBtn").click(function () {
            //    $("#tbody1").append(
            //        "<tr class=\‘AddTr\‘>"
            //        + "<td><input class=\"txtID\" type=\"text\" /></td>"
            //        + "<td><input class=\"txtXueHao\" type=\"text\" /></td>"
            //        + "<td><input class=\"txtName\" type=\"text\" /></td>"
            //        + "<td><input class=\"txtAge\" type=\"text\" /></td>"
            //        + "<td><input id=\"DeleteBtn\" type=\"button\" value=\"删除\"  class=\"btn btn-primary\"/></td>"
            //        + "</tr>"
            //     )
            //})

//保存
            $("#BaoCunBtn").click(function () {
                var str=""
                $(".AddTr").each(function(){
                    var xuehao=$(this).find("input").eq(0).val();
                    var name=$(this).find("input").eq(1).val();
                    var age=$(this).find("input").eq(2).val();
                    str += xuehao + ","+ name + ","+ age + "|";
                })
                //alert(str);
                $.ajax({
                    url: "/Student/Add?str=" + str,
                    type: "post",
                    dataType: "json",                
                    success: function (data) {
                        if (data.code == 1) {
                            alert(data.msg);
                            ShowList();
                        }
                        else {
                            alert(data.msg);
                        }
                    }
                })
            })

//修改
            $(document).on("click", ".Update", function () {
                //显示保存和取消按钮
                $(this).hide();  //修改按钮隐藏
                $(this).siblings().eq(0).hide();//删除按钮隐藏
                $(this).siblings().eq(1).hide(); //删除按钮隐藏
                $(this).siblings().eq(2).show(); //保存按钮显示
                $(this).siblings().eq(3).show(); //取消按钮显示
                var id = $(this).parent().siblings().eq(0).html();//获取学号
                var xuehao = $(this).parent().siblings().eq(1).html();//获取学号
                var name = $(this).parent().siblings().eq(2).html();//获取姓名
                var age = $(this).parent().siblings().eq(3).html();//获取年龄
                //修改当前行ta为文本框并显示值
                $(this).parent().siblings().eq(1).html("<input type=\"text\" class=\"txtXueHao\" value=\"" + xuehao + "\" />")
                $(this).parent().siblings().eq(2).html("<input type=\"text\" class=\"txtName\"  value=\"" + name + "\" />")
                $(this).parent().siblings().eq(3).html("<input type=\"text\" class=\"txtAge\" value=\"" + age + "\" />")
            });
            //修改保存
            $(document).on("click", ".BaoCun", function () {
                var id = $(this).parent().siblings().eq(0).html();
                var xuehao = $(this).parent().siblings().find("input[class=‘txtXueHao‘]").val();
                var name = $(this).parent().siblings().find("input[class=‘txtName‘]").val();
                var age = $(this).parent().siblings().find("input[class=‘txtAge‘]").val();
                //alert(id+","+xuehao + "," + name + "," + age);
                $.ajax({
                    url: "/Student/Update",
                    type: "post",
                    dataType: "json",
                    data: { id: id, xuehao: xuehao, name: name, age: age },
                    success: function (data) {
                        if (data.code == 1) {
                            alert(data.msg);
                            ShowList();
                        }
                        else {
                            alert(data.msg);
                        }
                    }
                })
            })
            //修改保存
            $(document).on("click", ".QuXiao", function () {
                alert("取消修改");
                ShowList();
            })

})
</script>

///控制器方法
    /// <summary>
        /// 显示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult StudentListShow()
        {
            return View();
        }
        /// <summary>
        /// 显示方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult StudentList()
        {
            var result = new BLL.StudentBLL().Show("");
            return Json(result);
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Add(string str)
        {
            str=str.TrimEnd(‘|‘);
            string[] array = str.Split(‘|‘);
            if (array == null || array.Length == 0)
            {
                return Json(new { code = 0, msg = "字符串异常" });
            }
            List<StudentModel> list = new List<StudentModel>();
            foreach (var item in array)
            {
                string[] arr = item.Split(‘,‘);
                if (arr == null || arr.Length == 0)
                {
                    return Json(new { code = 0, msg = "字符串异常" });
                }
                else
                {
                    StudentModel s = new StudentModel();
                    s.XueHao = arr[0];
                    s.StuName = arr[1];
                    s.Age = Convert.ToInt32(arr[2]);
                    list.Add(s);                    
                }
            }
            var result = new BLL.StudentBLL().AddList(list);
            if (result > 0)
            {
                return Json(new { code = 1, msg = "添加成功" });
            }
            else
            {
                return Json(new { code = 0, msg = "添加失败" });
            }     
        }
        /// <summary>
        /// 删除存储过程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteCCGC(int id)
        {
            var result = new BLL.StudentBLL().DeleteCCGC(id);
            if (result > 0)
            {
                return Json(new { code = 1, msg = "删除成功" });
            }
            else
            {
                return Json(new { code = 0, msg = "删除失败" });
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var result = new BLL.StudentBLL().Delete(id);
            if (result > 0)
            {
                return Json(new { code = 1, msg = "删除成功" });
            }
            else
            {
                return Json(new { code = 0, msg = "删除失败" });
            }
        }
        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Update(int id,string xuehao,string name,int age)
        {
            StudentModel stu = new StudentModel();
            stu.ID = id;
            stu.XueHao = xuehao;
            stu.StuName = name;
            stu.Age = age;
            var result = new BLL.StudentBLL().Update(stu);
            if (result > 0)
            {
                return Json(new { code = 1, msg = "修改成功" });
            }
            else
            {
                return Json(new { code = 0, msg = "修改失败" });
            }
        }
        /// <summary>
        /// 查询方法
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Select(string name)
        {
            var result = new BLL.StudentBLL().Show(name);
            return Json(result);
        }

///添加事物DAL写法
    /// <summary>
        /// 添加(事物)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public int AddList(List<StudentModel> m)
        {
            conn.Open();
            using (SqlTransaction st = conn.BeginTransaction())
            {
                try
                {
                    int i = 0;
                    foreach (var item in m)
                    {
                        string sql = "INSERT INTO StudentInfo VALUES(‘" + item.XueHao + "‘,‘" + item.StuName + "‘," + item.Age + ")";
                        SqlCommand com = new SqlCommand(sql, conn);
                        com.Transaction = st;
                        i = com.ExecuteNonQuery();
                    }
                    st.Commit();
                    conn.Close();
                    return i;
                }
                catch
                {
                    st.Rollback();
                    conn.Close();
                    return 0;
                }
            }
        }

////删除存储过程DAL写法
    /// <summary>
        /// 删除存储过程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteCCGC(int id)
        {
            SqlCommand com = new SqlCommand("Pro_Delete", conn);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@ID", id);
            com.Parameters.AddWithValue("@return_value", SqlDbType.Int);
            com.Parameters["@return_value"].Direction = ParameterDirection.ReturnValue;
            conn.Open();
            com.ExecuteNonQuery();
            var i =(int) com.Parameters["@return_value"].Value;
            return i;
        }

///创建删除存储过程
    CREATE PROCEDURE Pro_Delete
         @ID INT
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

-- Insert statements for procedure here
        DELETE FROM StudentInfo WHERE [email protected];
        RETURN @@ROWCOUNT
    END
    GO

<td><input type="checkbox" id="CheckAll" />全选</td>
<td><input type="checkbox"  name="CheckChild" value="@item.Gid " /></td>
        //全选
        $("#CheckAll").click(function(){
            $("input[name=‘CheckChild‘]").prop("checked",this.checked);
        })

时间: 2024-11-15 00:31:19

MVC增删改查整套(ajax,本页面,批量增)的相关文章

在ASP.NET MVC4中实现同页面增删改查,无弹出框02,增删改查界面设计

在上一篇"在ASP.NET MVC4中实现同页面增删改查,无弹出框01,Repository的搭建"中,已经搭建好了Repository层,本篇就剩下增删改查的界面了......今天的阳光真特么好,写完本篇,好出去在阳光下溜溜狗.散散步什么的,正所谓文武之道一张一弛,走神了,进入正题. 首先是一个View Model,在这里定义验证规则,提交和保存数据的时候还必须和领域模型映射. using System; using System.ComponentModel.DataAnnotat

Android数据库的增删改查和ListView以及页面跳转的实现

不多说什么,直接看代码:先创建一个person实体对象. import java.io.Serializable; public class Person implements Serializable{ private static final long serialVersionUID=1L; private Integer id; private String name; private String phone; private Integer amount; public Intege

5.Hibernate实现全套增删改查和ajax异步分页

1.1 创建如下oracle数据库脚本 1 drop sequence seq_stu; 2 3 create sequence SEQ_STU 4 minvalue 1 5 maxvalue 999999999999999999999999999 6 start with 1 7 increment by 1 8 cache 20; 9 10 drop table student; 11 12 create table STUDENT 13 ( 14 sid NUMBER not null,

BootstrapTable+KnockoutJS自定义T4模板快速生成增删改查页面

前言:上篇介绍了下ko增删改查的封装,确实节省了大量的js代码.博主是一个喜欢偷懒的人,总觉得这些基础的增删改查效果能不能通过一个什么工具直接生成页面效果,啥代码都不用写了,那该多爽.于是研究了下T4的语法,虽然没有完全掌握,但是算是有了一个大致的了解.于是乎有了今天的这篇文章:通过T4模板快速生成页面. KnockoutJS系列文章: JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(一) JS组件系列——BootstrapTable+KnockoutJS

MVC项目实践,在三层架构下实现SportsStore-11,使用Knockout实现增删改查

SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管理.图像上传......是不错的MVC实践项目,但该项目不是放在多层框架下开发的,离真实项目还有一段距离.本系列将尝试在多层框架下实现SportsStore项目,并用自己的方式实现一些功能. 本篇为"在三层架构下实现SportsStore"系列的第十一篇,包括: ■ 13.使用Knocko

BootstrapTable+KnockoutJS实现增删改查解决方案

BootstrapTable+KnockoutJS实现增删改查解决方案 前言:上篇介绍了下ko增删改查的封装,确实节省了大量的js代码.博主是一个喜欢偷懒的人,总觉得这些基础的增删改查效果能不能通过一个什么工具直接生成页面效果,啥代码都不用写了,那该多爽.于是研究了下T4的语法,虽然没有完全掌握,但是算是有了一个大致的了解.于是乎有了今天的这篇文章:通过T4模板快速生成页面. KnockoutJS系列文章: JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(

Struts2+Spring+Hibernate实现员工管理增删改查功能(一)之ssh框架整合

前言        转载请标明出处:http://www.cnblogs.com/smfx1314/p/7795837.html 本项目是我写的一个练习,目的是回顾ssh框架的整合以及使用.项目介绍:此项目主要有前台管理员通过登录进入员工管理系统页面,之后可以对员工列表进行常规的增删改查.以及部门列表的增删改查.IDE使用的是eclipse,个人感觉比较好用,不过最近我正在研究idea,数据库是mysql,前台主要以bootstrap为主. 这点是直接摘抄的 struts 控制用的 hibern

ActiveAndroid (二):如何进行增删改查

上一篇在这:Github开源框架:ActiveAndroid (一) 创建我们自己的数据库模型 创建我们自己的数据库模型是很简单的,只要创建一个有注释域的类,并把它命名为我们要用的名字就可以了.但是有两件事情我们必须要注意:一.你的类必须是Model类的子类,并且使用@Column进行注释.ActiveAndroid 会处理类内的基本数据类型以及和其他表间的关系或者是日期类.二.ActiveAndroid 会在你的表中自动创建一个ID字段.这个字段会自动地递增. ActiveAndroid将使用

python增删改查(四)

###增删改查 names = ["zhangding","wangxu","wudong","cheng"] #增 names.append("zhangzhengxin") #增加 print(names) names.insert(2,"liu") #插入 names.insert(1,"shun") print(names) #删 #names.remove(