.net EF框架—增删改查—ajax删除

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_40900884/article/details/82154454

1.数据库代码:(两个表)

use master
go
if exists(select * from sys.databases where name='QU')
drop database QU
create database QU
use QU
create table class
(
classID int not null identity primary key,
classname varchar(10) not null
)

create table studentinfo
(
ID int not null identity primary key,
studentname varchar(10) not null,
age int not null,
phone varchar(50) not null,
email varchar(50) not null,
Fk_classID int references class(classID)
)
insert into class values('1班')
insert into class values('2班')
insert into class values('3班')
insert into studentinfo values('木子洋1',12,'12345678901','12345@qq.com',1)
insert into studentinfo values('木子洋2',13,'12345678902','12345@qq.com',2)
insert into studentinfo values('木子洋3',14,'12345678903','12345@qq.com',3)
insert into studentinfo values('木子洋4',15,'12345678904','12345@qq.com',1)
insert into studentinfo values('木子洋5',16,'12345678905','12345@qq.com',2)
select * from studentinfo

2.创建EF框架以及Web项目——index.aspx(查询页面)

3.index.aspx代码

 <form id="form1" runat="server">
    <div>
        
            <table style="width: 100%;">
               
                <tr>
                    <td>编号</td>
                    <td>姓名</td>
                    <td>年龄</td>
                    <td>手机</td>
                     <td>邮箱</td>
                    <td>班级</td>
                     <td>操作</td>
                </tr>
                   <asp:Repeater ID="Repeater1" runat="server">
                       <ItemTemplate>
                            <tr>
                    <td><%#Eval("ID") %></td>
                    <td><%#Eval("studentname") %></td>
                     <td><%#Eval("age") %></td>
                     <td><%#Eval("phone") %></td>
                      <td><%#Eval("email") %></td>
                      <td><%#Eval("classname") %></td>
                      <td>
                              <a href ="update.aspx?userid=<%#Eval("ID") %>">修改</a>
                              <a href="javascript:;"  class="del" onclick="del(<%#Eval("ID") %>)" >删除</a>
                             
                      </td>
                </tr>
                       </ItemTemplate>
        </asp:Repeater>
            </table>
        <asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
       
    </div>
    </form>

index.aspx设计图

查询

  //声明一个EF上下文对象
                QUEntities db = new QUEntities();
                //查询语句
                var select = from c in db.@class
                             join d in db.studentinfo on c.classID equals d.Fk_classID
                             select new { c.classname, d.age, d.email, d.ID, d.phone, d.studentname };
              
                //在Repeater中显示
                Repeater1.DataSource = select.ToList();
                Repeater1.DataBind();

添加

add.aspx页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="add.aspx.cs" Inherits="WebApplication1.add" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">
        .auto-style1 {
            height: 20px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3>添加新学员</h3>
        <table style="width: 100%;">
            <tr>
                <td class="auto-style1">姓名</td>
                <td class="auto-style1">
                    <asp:TextBox ID="Tbname" runat="server"></asp:TextBox></td>
            
            </tr>
             <tr>
                <td class="auto-style1">年龄</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbage" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">手机</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbphone" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">邮箱</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbemail" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">班级</td>
                <td class="auto-style1">
                    <asp:DropDownList ID="DropDownList1" runat="server">
                    </asp:DropDownList>
                   </td>
            
            </tr>

              <tr>
                <td class="auto-style1">&nbsp;</td>
                <td class="auto-style1">
                    <asp:Button ID="Button1" runat="server" Text="添加学员" OnClick="Button1_Click" />
                   </td>
            
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

add.aspx页面设计图

添加后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class add : System.Web.UI.Page
    {
  //声明一个EF上下文对象
       QUEntities db = new QUEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //下拉框显示
                var select = from c in db.@class select c;
                DropDownList1.DataSource = select.ToList();
                DropDownList1. DataValueField = "classID";
                DropDownList1.DataTextField = "classname";
                DropDownList1.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //添加信息
            studentinfo insert = new WebApplication1.studentinfo();
            insert.studentname = Tbname.Text;
            insert.age =Convert.ToInt16( tbage.Text);
            insert.phone = tbphone.Text;
            insert.Fk_classID = Convert.ToInt32(DropDownList1.SelectedValue);
            insert.email = tbemail.Text;
            //将信息添加到数据库
            db.studentinfo.Add(insert);
            //将所有的更改保存到数据库
            int i = db.SaveChanges();
            if (i>0)
            {
                Response.Write("<script>alert('成功');location.href='index.aspx';</script>");

            }

            else
            {
                Response.Write("<script>alert('失败');</script>");
            }

        }
    }
}

修改

update.aspx设计图

update.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="update.aspx.cs" Inherits="WebApplication1.update" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <h3>修改学员</h3>
        <table style="width: 100%;">
            <tr>
                <td class="auto-style1">姓名</td>
                <td class="auto-style1">
                    <asp:TextBox ID="Tbname" runat="server"></asp:TextBox></td>
            
            </tr>
             <tr>
                <td class="auto-style1">年龄</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbage" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">手机</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbphone" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">邮箱</td>
                <td class="auto-style1">
                    <asp:TextBox ID="tbemail" runat="server"></asp:TextBox></td>
            
            </tr>
               <tr>
                <td class="auto-style1">班级</td>
                <td class="auto-style1">
                    <asp:DropDownList ID="DropDownList1" runat="server">
                    </asp:DropDownList>
                   </td>
            
            </tr>

              <tr>
                <td class="auto-style1">&nbsp;</td>
                <td class="auto-style1">
                    <asp:Button ID="Button1" runat="server" Text="修改学员" OnClick="Button1_Click" />
                   </td>
            
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

update.aspx后台代码

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class update : System.Web.UI.Page
    {
        //声明一个EF上下文对象
        QUEntities db = new QUEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //下拉框显示
                var select = from c in db.@class select c;
                DropDownList1.DataSource = select.ToList();
                DropDownList1.DataValueField = "classID";
                DropDownList1.DataTextField = "classname";
                DropDownList1.DataBind();
                //获取到id
                int id = Convert.ToInt32(Request.QueryString["userid"]);
                //根据ID查询
                var xinashi = db.studentinfo.Where(p => p.ID == id).FirstOrDefault();
                //文本框显示值
                Tbname.Text = xinashi.studentname;
                tbage.Text = xinashi.age.ToString();
                tbphone.Text = xinashi.phone;
                tbemail.Text = xinashi.email;
                DropDownList1.SelectedValue = xinashi.Fk_classID.ToString();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //获取到id
            int id = Convert.ToInt32(Request.QueryString["userid"]);
            //根据ID查询
            var insert = db.studentinfo.Where(p => p.ID == id).FirstOrDefault();
            insert.studentname = Tbname.Text;
            insert.age = Convert.ToInt16(tbage.Text);
            insert.phone = tbphone.Text;
            insert.Fk_classID = Convert.ToInt32(DropDownList1.SelectedValue);
            insert.email = tbemail.Text;
            db.studentinfo.Attach(insert);
            db.Entry(insert).State = EntityState.Modified;
            int i = db.SaveChanges();
            if (i>0)
            {
                Response.Write("<script>alert('更新成功');location.href='index.aspx';</script>");

            }
            else
            {
                Response.Write("<script>alert('更新失败')</script>");
            }
        }
    }
}

删除(EF+ajax)

1.新建一个类(json)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class ReusltJson
    {
        public bool date { get; set; }
        public string mess { get; set; }
        public ReusltJson() { }
        public ReusltJson(bool date,string mess)
        {
            this.date = date;
            this.mess = mess;    
        }

    }
}

2.新建一个一般应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    /// <summary>
    /// DElete 的摘要说明
    /// </summary>
    public class DElete : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        //EF实例化上下文
        QUEntities db = new QUEntities();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
           //获取到id
            int  id =Convert.ToInt32( context.Request.Form["c"]);
           //根据id查询
            var a = db.studentinfo.FirstOrDefault(s=>s.ID==id);
            //如果没有数据,已经删除
            if (a == null)
            {
                ReusltJson result = new WebApplication1.ReusltJson(false, "已经删除");
                JavaScriptSerializer js = new JavaScriptSerializer();
                string join = js.Serialize(result);
                context.Response.Write(join);
                return;
            }
            //删除
            db.studentinfo.Remove(a);
            int i = db.SaveChanges();
            //判断是否删除
            if (i>0)
            {
                //实例化json并添加数据
                ReusltJson result = new WebApplication1.ReusltJson(true, "删除成功");
                JavaScriptSerializer js = new JavaScriptSerializer();
                string join = js.Serialize(result);
                context.Response.Write(join);
            }
          
            else
            {
                ReusltJson result = new WebApplication1.ReusltJson(false, "删除失败");
                JavaScriptSerializer js = new JavaScriptSerializer();
                string join = js.Serialize(result);
                context.Response.Write(join);

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

3.ajax代码(写在index)

注意:删除按钮  <a href="javascript:;" class="del" οnclick="del(<%#Eval("ID") %>)" >删除</a>

  <script>
  
         function del(id)
         {
             if(confirm("你确定要删除吗?")){
                  $.post("DElete.ashx",
             { c: id },
              function (d) {
                  if (d.data=true) {
                      alert(d.mess);
                     location.reload();
             }
             else {
                      alert(d.mess );
             }
             }, "json");
         
             }
                   
       }
              
     
     </script>

 

展开阅读全文

没有更多推荐了,返回首页