使用ajax调用和webmethod可以有多个INSERT语句吗?

时间:2017-03-07 18:50:48

标签: jquery asp.net json ajax

我目前正在使用JSON对象和带webmethod的ajax调用将多行记录插入数据库。

换句话说,我们可以动态地向表中添加更多行,并在数据被字符串化为JSON对象后使用ajax调用和webmethod成功地将这些行插入数据库。

这对我们很有用。

我们目前面临的问题是,我们希望在此web方法中有多个INSERT语句,但它不起作用。

例如,这是我的JS与数据联系人类:

   <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />  
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on("click", "#empAdd", function () { //
                var rowCount = $('.data-contact-person').length + 1;
                var contactdiv = '<tr class="data-contact-person0">' +
                    '<td><input type="text" style="width:200px;" name="employeename' + rowCount + '" placeholder="Your name..." class="form-control employeename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="employeetitle' + rowCount + '" placeholder="Your title..." class="form-control employeetitle01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="employeeemail' + rowCount + '" placeholder="Your email address..." class="form-control employeeemail01" /></td>' +
                    '<td style="width:200px;"><button type="button" id="empAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' +
                    '<button type="button" id="empDeletem" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
                    '</tr>';
                $('#emptable').append(contactdiv); // Adding these controls to Main table class
            });

        $(document).ready(function () {
            $(document).on("click", "#btnAdd", function () { //
                var rowCount = $('.data-contact-person').length + 1;
                var contactdiv = '<tr class="data-contact-person">' +
                    '<td><input type="text" style="width:200px;" name="sourcename' + rowCount + '" placeholder="Name of income source..." class="form-control sourcename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceaddress' + rowCount + '" placeholder="Address of income source..." class="form-control sourceaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceincome' + rowCount + '" placeholder="Income..." class="form-control sourceincome01" /></td>' +
                    '<td style="width:200px;"><button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' +
                    '<button type="button" id="btnDelete1" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
                    '</tr>';
                $('#maintable').append(contactdiv); // Adding these controls to Main table class
            });


            $(document).on("click", ".deleteContact", function () {
                $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls 
            });

            function getAllEmpData() {
                var data = [];
                $('tr.data-contact-person').each(function () {
                    var ename = $(this).find('.employeename01').val();
                    var etitle = $(this).find('.employeetutle01').val();
                    var email = $(this).find('.employeeemail01').val();
                    var sname = $(this).find('.sourcename01').val();
                    var saddress = $(this).find('.sourceaddress01').val();
                    var sincome = $(this).find('.sourceincome01').val();
                    var alldata = {
                        'empname': ename,
                        'emptitle': etitle,
                        'mySIncome': email,
                        'empmail': sname,
                        'mySAddress': saddress,
                        'mySIncome': sincome
                    }
                    data.push(alldata);
                });
                console.log(data);
                return data;
            }

            $("#btnSubmit").click(function () {
                var data = JSON.stringify(getAllEmpData());
                console.log(data);
                $.ajax({
                    url: 'disclosures.aspx/SaveData',
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ 'empdata': data }),
                    success: function () {
                        alert("Data Added Successfully");
                    },
                    error: function(xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
            });
        });
    </script>
<style type="text/css">
    .bs-example{
        margin-left: 250px;
        margin-top: 30px;
    }
</style>
</head>
<body> 
   <div class="bs-example"> 
    <form id="form1" runat="server">  
        <div class="container">  
            <h2>closure Forms</h2>  

            <table id="emptable">  
                <thead>  
                    <tr>  
                        <th>Employee Name</th>  
                        <th>Title</th>  
                        <th>Email</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" style="width:200px;" name="employeename" class="form-control employeename01" placeholder="Your name..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="employeetitle" class="form-control employeetitle01" placeholder="Your title..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="employeeemail" class="form-control employeeemail01" placeholder="Your email address..." /></td>  
                        <td>  
                        </td>  
                    </tr>  
                </tbody>  
            </table><br /><br />
              <span style="font-weight:bold;font-size:16px;color:steelblue;">Name and address of income source greater than $100,000.00</span> 
            <table id="maintable">  
                <thead>  
                    <tr>  
                        <th>Name</th>  
                        <th>Address</th>  
                        <th>Income</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" style="width:200px;" name="sourcename" class="form-control sourcename01" placeholder="Name of income source..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceaddress" class="form-control sourceaddress01" placeholder="Address of income source..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceincome" class="form-control sourceincome01" placeholder="Income..." /></td>  
                        <td style="width:200px;">  
                            <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
                        </td>  
                    </tr>  
                </tbody>  
            </table><br /><br /> 
            <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-center btn-sm">Submit</button> 
        </div>  
'//Then the SaveData webmethod:

    <WebMethod()> _
    Public Shared Function SaveData(empdata As String) As String
        Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
        Dim s As String
        Dim sql As String
        Using con = New SqlConnection(Constr)
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            For Each data As Employee In serializedData
                s = "INSERT INTO Employees(EmployeeNamee,email,empTitl) Values (@ename, @title,@email)"
                sql = "Select Max(employeeID) From Employees"
                'Response.Write(s)
                'Response.End()
                ' Dim con As New SqlConnection(Constr)
                Dim cmd As New SqlCommand(s, con)
                cmd.Parameters.AddWithValue("@ename", data.empName)
                cmd.Parameters.AddWithValue("@title", data.empMail)
                cmd.Parameters.AddWithValue("@email", data.empTitle)
                ' con.Open()
                cmd.ExecuteNonQuery()
                cmd.CommandText = sql
                Dim ID = cmd.ExecuteScalar() '//get retrieve last inserted key to be inserted into sourceDetails table
            Next
            For Each data As Employee In serializedData
                Using cmd = New SqlCommand("INSERT INTO SourceDetails(sourcename, sourceaddress, sourceincome,employeeID) VALUES(@sname, @saddress,@sincome, @ID)")
                    cmd.CommandType = CommandType.Text
                    cmd.Parameters.AddWithValue("@sname", data.mySource)
                    cmd.Parameters.AddWithValue("@saddress", data.mySAddress)
                    cmd.Parameters.AddWithValue("@sincome", data.mySIncome)
                    cmd.Parameters.AddWithValue("@ID", " & ID & ")
                    '  cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
                    cmd.Connection = con
                    cmd.ExecuteNonQuery()
                End Using
            Next
            con.Close()
        End Using
        Return Nothing
    End Function
End Class

    Public Class Employee
        Public Property mySource() As String
            Get
                Return m_mySource
            End Get
            Set(value As String)
                m_mySource = value
            End Set
        End Property
        Private m_mySource As String
        Public Property mySAddress() As String
            Get
                Return m_mySAddress
            End Get
            Set(value As String)
                m_mySAddress = value
            End Set
        End Property
        Private m_mySAddress As String
        Public Property mySIncome() As String
            Get
                Return m_mySIncome
            End Get
            Set(value As String)
                m_mySIncome = value
            End Set
        End Property
        Private m_mySIncome As String
        Public Property empName() As String
            Get
                Return m_empName
            End Get
            Set(value As String)
                m_empName = value
            End Set
        End Property
        Private m_empName As String
        Public Property empMail() As String
            Get
                Return m_empMail
            End Get
            Set(value As String)
                m_empMail = value
            End Set
        End Property
        Private m_empMail As String
        Public Property empTitle() As String
            Get
                Return m_empTitle
            End Get
            Set(value As String)
                m_empTitle = value
            End Set
        End Property
        Private m_empTitle As String

当我尝试添加另一个名为 data-contact-person2 的类时,需要将另一个INSERT语句添加到web方法中,代码会出现错误,表示@parameter @sname是必需的但没有提供。

那么,无论如何操纵webmethod以允许多个INSERT语句,或者我必须有多个单独的web方法来使我的代码工作?

很抱歉这长码。

0 个答案:

没有答案