使用ajax将数据插入数据库

时间:2013-07-11 05:26:04

标签: javascript c# ajax insert using

我使用ajax在数据库中插入数据

我的默认.aspx文件如下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ajax Demo</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {

            $("#<%= btn_Insert.ClientID %>").click(function () {

                //var name = $('#<%=txt_name.ClientID%>').val();
                //var email=$('#<%=txt_email.ClientID%>').val()

                var email = document.getElementById('txt_email').value;
                var name = document.getElementById('txt_name').value;

                //alert("{'Name':'" + name + "', 'Email':'" + email + "'}");
                $.ajax({

                    type: 'POST',

                    contentType: "application/x-www-form-urlencoded; charset=utf-8",

                    data: "Name=" + name + "&Email=" + email,

                   //data: $('#form1')

                    async: true,

                    success: function (response, data)
                    {
                        $('#txt_name').val('');

                        $('#txt_email').val('');

                        alert("Record Has been Saved in Database");

                        alert(response.data.name);
                    },

                    error: function () {
                        console.log('there is some error');
                    }

                });
                return false;
            });
        });
 </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            Name : <asp:TextBox ID="txt_name" runat="server" ClientIDMode="Static"></asp:TextBox>
        </p>

        <p>
            E-mail : <asp:TextBox ID="txt_email" runat="server" ClientIDMode="Static"></asp:TextBox>
        </p>

        <p>
            <asp:Button ID="btn_Insert" runat="server" Text="INSERT" OnClick="btn_Insert_Click"/>
        </p>
    </div>
    </form>
</body>
</html>

我的.cs文件如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string Name = Request["Name"];
        string Email = Request["Email"];

        InsertMethod(Name, Email);
    }

    SqlCommand cmd;

    public Boolean InsertMethod(string Name, string Email)
    {
       SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);

        cmd = new SqlCommand("insert into dbo.Demo_AJAX (Name,Email)values (@name,@email)", conn);
        cmd.CommandType =CommandType.Text;
        cmd.Parameters.AddWithValue("@name",Name);
        cmd.Parameters.AddWithValue("@email", Email);
        try
        {
            conn.Open();
            //cmd.ExecuteNonQuery();
            int affected = cmd.ExecuteNonQuery();

            if (affected == 1)
            {
                //Response.Write("Bhargav");
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
            return false;
        }
        finally
        {
            conn.Close();
        }
    }

    protected void btn_Insert_Click(object sender, EventArgs e)
    {
    }
}

当我运行时,它会在数据库中插入一个空白数据。

我不知道如何解决它。

请任何人帮助我。

1 个答案:

答案 0 :(得分:0)

使用webmethod然后它的工作。

添加名称空间

using System.Web.Services;

改变您的方法

[WebMethod]
public static Boolean InsertMethod(string Name, string Email)

并删除

<asp:Button ID="btn_Insert" runat="server" Text="INSERT" />

并从.CS页面中删除点击事件 然后它的工作。