Ajax+JQuery+LinQ实现增删改查无刷新(转)

转自:http://blog.csdn.net/yi_iy/article/details/6326488

 

开发工具SQL server2008/vs2010.

采用三层框架(BLL/DAL/UI).

首先在SQL server2008中创建名为UserInfo的数据库,表名为tb_user包含字段UserID(主键/自动标识符为1)/UserName/Sex/Birthday/Address/Phone/Remark.

在VS2010中新建项目LinQU,在项目中分别添加类库BLL/DAL/Model与网站Web.

在Model类库中添加名为DataUser的LinQ to SQL类,点开服务器资源管理器连接到本地数据库,把表拖拽到DataUser中.

 

在DAL中添加Duser类,添加Model类库、System.Data.Linq的引用,然后代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;

namespace DAL
{
    public class DUser
    {

        //引用Model中创建的LinQ to SQL 类
        DataUserDataContext db = new DataUserDataContext();


        //查询用户表信息

        public IQueryable SelectUser()
        {
            var user = from u in db.tb_user
                       select u;
            return user;
        }


        //添加用户信息

        public void InserUser(tb_user tbuser)
        {
            tb_user user = new tb_user();
            user.Address = tbuser.Address;
            user.Birthday = tbuser.Birthday;
            user.Phone = tbuser.Phone;
            user.Remark = tbuser.Remark;
            user.Sex= tbuser.Sex;
            user.UserName = tbuser.UserName;
            db.tb_user.InsertOnSubmit(user);
            db.SubmitChanges();
        }

 

        //修改用户信息

        public void UpdateUser(tb_user tbuser)
        {
            tb_user user = db.tb_user.Single(u=>u.UserID==tbuser.UserID);
            user.Address = tbuser.Address;
            user.Birthday = tbuser.Birthday;
            user.Phone = tbuser.Phone;
            user.Remark = tbuser.Remark;
            user.Sex = tbuser.Sex;
            user.UserName = tbuser.UserName;
            db.SubmitChanges();
        }

 

        //删除用户信息

        public void DeleteUser(tb_user tbuser)
        {
            tb_user user = db.tb_user.Single(u=>u.UserID==tbuser.UserID);
            db.tb_user.DeleteOnSubmit(user);
            db.SubmitChanges();
        }


    }
}

 

 

在BLL中添加BUser类,添加Model/DAL类库的引用,然后代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Model;

namespace BLL
{
    public class BUser
    {

        //实例化DUser类
        static DUser duser = new DUser();

 

        //查询用户表信息
        public static IQueryable SelectUser()
        {
            return duser.SelectUser();
        }

 

        //添加用户信息
         public static void InserUser(tb_user user)
        {
            duser.InserUser(user);
        }

 

        //修改用户信息

        public static void UpdateUser(tb_user user)
        {
            duser.UpdateUser(user);
        }

 

        //删除用户信息

        public static void DeleteUser(tb_user user)
        {
            duser.DeleteUser(user);
        }
    }
}

 

在网站Web中,添加对BLL/Model类库的引用,新建名为UserInfo的窗体:

 

在<head>标签中添加代码如下:

 

<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js">

     //VS2010中自带的Scripts/jquery-1.4.1.min.js

     </script>


    <script language="javascript" type="text/javascript" >

      //无刷新绑定函数
        function Bind() {
            $.ajax({
                type: "GET",
                url: "UserInfo.aspx",
                datatype: "html",
                data: "type=Bind&" + Math.random(),
                success: function (msg) {
                    $("#queryResult").html(msg);
                }
            });
        }

 

       //添加用户信息

        function Insert() {
            $.ajax({
                type: "GET",
                url: "UserInfo.aspx",
                datatype: "html",
                data: "&UserName=" + escape($("#txtusername").val()) + "&Sex=" + escape($("#txtsex").val())
                + "&Address=" + escape($("#txtaddress").val()) + "&Brithday=" + $("#txtbrithday").val() + "&Phone="
                + escape($("#txtphone").val()) + "&Remark=" + escape($("#txtremark").val()) + "&type=Insert&" + Math.random(),
                success: function (msg) {
                    if (msg == "添加成功") {
                        alert("添加成功!");
                        Bind();
                    }
                    else {
                        alert(msg);
                    }
                }
            });
        }

 

       //删除用户

        function Delete() {
            $.ajax({
                type: "GET",
                url: "UserInfo.aspx",
                datatype: "html",
                data: "UserID=" + $("#txtuserid").val() + "&type=Delete&" + Math.random(),
                success: function (msg) {
                    if (msg == "删除成功") {
                        alert("删除成功!");
                        Bind();
                    }
                    else {
                        alert(msg);
                    }
                }
            });

        }

 

       //修改用户

        function Update() {
            $.ajax({
                type: "GET",
                url: "UserInfo.aspx",
                datatype: "html",
                data: "UserID=" + $("#txtuserid").val() + "&UserName=" + escape($("#txtusername").val()) + "&Sex=" + escape($("#txtsex").val())
                + "&Address=" + escape($("#txtaddress").val()) + "&Brithday=" + $("#txtbrithday").val() + "&Phone="
                + escape($("#txtphone").val()) + "&Remark=" + escape($("#txtremark").val()) + "&type=Update&" + Math.random(),
                success: function (msg) {
                    if (msg == "修改成功") {
                        alert("修改成功!");
                        Bind();
                    }
                    else {
                        alert(msg);
                    }
                }
            })
        }

 

    </script>
    </head>

 

 

在<form>标签中代码如下:

 

    <form id="form1" runat="server">
   

    <table width="100%">
    <tr><td colspan="4"><div id="queryResult">
                <asp:GridView ID="GridUser" runat="server" AutoGenerateColumns="False" 
                    DataKeyNames="UserID" Height="142px" Width="658px">
                    <Columns>
                        <asp:BoundField DataField="UserID" HeaderText="用户编号" />
                        <asp:BoundField DataField="UserName" HeaderText="用户名"  />
                        <asp:BoundField DataField="Sex" HeaderText="性别"/>
                        <asp:BoundField DataField="Birthday" HeaderText="出生日期"  />
                        <asp:BoundField DataField="Address" HeaderText="地址"   />
                        <asp:BoundField DataField="Phone" HeaderText="电话"    />
                        <asp:BoundField DataField="Remark" HeaderText="备注" />
                        </Columns>
                </asp:GridView>
    </div></td></tr>
        <tr><td>用户编号:</td><td>
            <input id="txtuserid" type="text" /></td><td>用 户 名:</td><td>
            <input id="txtusername" type="text" onblur="check()" /><asp:Label ID="Label1" 
                runat="server" ForeColor="Red"></asp:Label>
            </td></tr>
            <tr><td>性&nbsp;&nbsp;&nbsp; 别:</td><td>
                <input id="txtsex" type="text" /></td><td>出生日期:</td><td>
                <input id="txtbrithday" type="text" /></td></tr>
                <tr><td>地&nbsp;&nbsp;&nbsp; 址:</td><td>
                    <input id="txtaddress" type="text" /></td><td>电&nbsp;&nbsp;&nbsp; 话:</td><td>
                    <input id="txtphone" type="text" /></td></tr>
                    <tr><td>备&nbsp;&nbsp;&nbsp; 注:</td><td colspan="3">
                        <textarea rows="" cols="" id="txtremark" name="S1"></textarea></td></tr>
                        <tr><td></td><td>
                            <input id="btnAdd" type="button"  value="添加" onclick="Insert()"/>&nbsp;
                            <input id="btnUpdate" type="button"  value="修改"  onclick="Update()" />&nbsp;
                            <input id="btnDelete" type="button" value="删除" onclick="if(confirm('是否删除'))Delete()"/>
                            </td><td></td><td>
                            </td></tr>
    </table>
    </form>

 

 

后台代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using System.IO;
using Model;

public partial class UserInfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["type"] == "Bind")
        {
            Bind();
        }
        if (!IsPostBack)
        {
            GridUser.DataSource = BUser.SelectUser();
            GridUser.DataBind();
        }

        if (Request.QueryString["type"] == "Insert")
        {
            string str = Insert();
            Response.Write(str);
            Response.End();
        }
        if (Request.QueryString["type"] == "Delete")
        {
           string str= Delete();
            Response.Write(str);
            Response.End();
        }
        if (Request.QueryString["type"] == "Update")
        {
            string str = Update();
            Response.Write(str);
            Response.End();
        }

    }

 

    //修改用户信息

    private string Update()
    {
        try
        {
            tb_user user = new tb_user();
            user.UserID = Convert.ToInt32(Request.QueryString["UserID"]);
            user.UserName = Request.QueryString["UserName"];
            user.Sex = Request.QueryString["Sex"];
            user.Remark = Request.QueryString["Remark"];
            user.Phone = Request.QueryString["Phone"];
            user.Birthday = Convert.ToDateTime(Request.QueryString["Brithday"].ToString());
            user.Address = Request.QueryString["Address"];
            BUser.UpdateUser(user);
            return "修改成功";

        }
        catch(Exception ex)
        {
            return ex.Message;
        }
    }

 

    //删除用户

    private string Delete()
    {
        try
        {
            tb_user user = new tb_user();
            user.UserID =Convert.ToInt32(Request.QueryString["UserID"].ToString());
            BUser.DeleteUser(user);
            return "删除成功";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    
    }

 

   //添加用户信息
    private string Insert()
    {
        try
        {
            tb_user user = new tb_user();
            user.UserName = Request.QueryString["UserName"];
            user.Sex = Request.QueryString["Sex"];
            user.Remark = Request.QueryString["Remark"];
            user.Phone = Request.QueryString["Phone"];
            user.Birthday = Convert.ToDateTime(Request.QueryString["Brithday"].ToString());
            user.Address = Request.QueryString["Address"];
            BUser.InserUser(user);
            return "添加成功";

        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

 

    //无刷新绑定
    private void Bind()
    {
        GridUser.DataSource = BUser.SelectUser();
        GridUser.DataBind();

        StringWriter tw = new StringWriter();
        Html32TextWriter writer = new Html32TextWriter(tw);
        GridUser.RenderControl(writer);
        writer.Close();
        Response.Write(tw.ToString());
        Response.End();

    }

    //重绘服务器控件一定一定要重写这个方法
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
}

 

转自:http://blog.csdn.net/yi_iy/article/details/6326488

posted @ 2014-01-01 23:48  weegoood  阅读(271)  评论(0编辑  收藏  举报