如何从一个表中检索最后插入的ID并使用webmethods将其插入另一个表?

时间:2017-03-11 22:55:37

标签: asp.net ajax vb.net

我有几个表,其中一个名为Employees。

它与EmployeeID的其他几个表有关。

我们想在Employees表中插入数据,检索最后插入的ID,然后立即将其插入到另一个表中,可能还有更多的表。

我以前做了好几次。这次有什么不同,我们正在使用ajax调用,JSON对象和webmethods这样做。

将记录插入Employees表有效但检索最后插入的ID并尝试将其插入其他表中会产生一个错误,指出@parameter是必需的但未提供。

使用ajax调用和webmethods是不可能的?

这是我迄今为止尝试做的失败。

很抱歉,我仍然尽可能缩短代码,同时仍提供相关代码。

<!DOCTYPE html>
<!-- saved from url=(0048)http://keniginc.com/WilogIncomeTax/closures.html -->
<html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Closure Forms</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">

    <script type="text/javascript">
        $(document).ready(function () {
            $(document).on("click", "#btnAdd0", function () { //
                var rowCount = $('.data-contact-person0').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="btnAdd0" class="btn btn-xs btn-primary classAdd">Add More</button>' +
                    '<button type="button" id="btnDelete0" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
                    '</tr>';
                $('#maintable0').append(contactdiv); // Adding these controls to Emp table class
            });

            $(document).ready(function () {
                $(document).on("click", "#btnAdd1", function () { //
                    var rowCount = $('.data-contact-person1').length + 1;
                    var contactdiv = '<tr class="data-contact-person1">' +
                        '<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="btnAdd1" 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>';
                    $('#maintable1').append(contactdiv); // Adding these controls to Source 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-person0').each(function () {
                                    var ename = $(this).find('.employeename01').val();
                                    var etitle = $(this).find('.employeetitle01').val();
                                    var email = $(this).find('.employeeemail01').val();
                                    var alldata = {
                                        'emplName': ename,
                                        'emplTitle': etitle,
                                        'empMail': email
                                    }
                                    data.push(alldata);
                                });
                                console.log(data);
                                return data;
                            }
                            function getAllSourcepData() {
                                var data = [];
                                $('tr.data-contact-person1').each(function () {
                                    var sname = $(this).find('.sourcename01').val();
                                    var saddress = $(this).find('.sourceaddress01').val();
                                    var sincome = $(this).find('.sourceincome01').val();
                                    var alldata = {
                                        'mySource': sname,
                                        'mySAddress': saddress,
                                        'mySIncome': sincome
                                    }
                                    data.push(alldata);
                                });
                                console.log(data);
                                return data;
                            }
                            $("#btnSubmit").click(function (event) {
                                event.preventDefault();
                                var empComplete = false, sourceComplete = false;
                                function checkComplete() {
                                    if (empComplete && sourceComplete) {
                                        $("#result").text("All complete");
                                    }
                                }
                                $("#result").text("");
                                var data = JSON.stringify(getAllEmpData());
                                console.log(data);
                                $.ajax({
                                    url: 'testpost.asp.net/saveEmpData',
                                    type: 'POST',
                                    contentType: 'application/json; charset=utf-8',
                                    data: JSON.stringify({ 'empdata': data }),
                                    success: function () {
                                        empComplete = true;
                                        checkComplete();
                                    },
                                    error: function (xhr, status, error) {
                                        alert(xhr.responseText);
                                    }
                                });
                                var data = JSON.stringify(getAllSourcepData());
                                console.log(data);
                                $.ajax({
                                     url: 'testpost.asp.net/saveSourceData',
                                    type: 'POST',
                                    contentType: 'application/json; charset=utf-8',
                                    data: JSON.stringify({ 'empdata': data }),
                                    success: function () {
                                        sourceComplete = true;
                                        checkComplete();
                                    },
                                    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" novalidate="novalidate">
        <div class="container">
            <h2>Dynamic Forms</h2>
            <table style="width:55%" id="maintable0">
                <thead>
                    <tr>
                        <th>Employee Name</th>
                        <th>Title</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="data-contact-person0">
                        <td>
                            <input type="text" style="width:200px;" id="employeeename" 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>
            <table style="width:73%" id="maintable1">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Income</th>
                    </tr>
                </thead>
                <tbody>
                    <tr class="data-contact-person1">
                        <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>
            <input type="submit" id="btnSubmit" class="btn btn-primary btn-md pull-center btn-sm" value="Submit">
            <output id="result"></output>

            <br><br><br>
        </div>
    </form>
  </div>
</body></html>


//Codefile

<WebMethod(EnableSession:=True)> _
    Public Shared Function SaveEmpData(empdata As String) As String
        Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
        Using con = New SqlConnection(Constr)
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            '  Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
            '  Dim ID As Integer = cmdGetKey.ExecuteScalar()

            For Each data As Employee In serializedData
                Using cmd1 = New SqlCommand("INSERT INTO Employees(EmployeeName,empTitle,email) Values (@ename, @title,@email)")
                    cmd1.CommandType = CommandType.Text
                    cmd1.Parameters.AddWithValue("@ename", data.emplName)
                    cmd1.Parameters.AddWithValue("@title", data.emplTitle)
                    cmd1.Parameters.AddWithValue("@email", data.empMail)
                    cmd1.Connection = con
                    cmd1.ExecuteNonQuery()
                    Dim cmdGetKey As New SqlCommand("SELECT @@IDENTITY", con)
                    Dim ID As Integer = cmdGetKey.ExecuteScalar()
                    HttpContext.Current.Session("empID") = ID
                End Using
            Next
            con.Close()
        End Using
        Return Nothing
    End Function

    <WebMethod(EnableSession:=True)> _
    Public Shared Function SaveSourceData(empdata As String) As String
        Dim serializedData = JsonConvert.DeserializeObject(Of List(Of SourcDetails))(empdata)
        Using con = New SqlConnection(Constr)
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            '  Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
            '  Dim ID As Integer = cmdGetKey.ExecuteScalar()

            For Each data As SourcDetails 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", HttpContext.Current.Session("empID"))
                    '  cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
                    cmd.Connection = con
                    cmd.ExecuteNonQuery()
                End Using
            Next
            con.Close()
        End Using
        Return Nothing
    End Function
Public Class Employee
    Public Property emplName() 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 emplTitle() As String
        Get
            Return m_empTitle
        End Get
        Set(value As String)
            m_empTitle = value
        End Set
    End Property
    Private m_empTitle 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
End Class
Public Class SourcDetails
    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

End Class

1 个答案:

答案 0 :(得分:0)

我相信我已经解决了这个问题。

由于必须将数据插入Employees表中以便检索以后要使用的最后插入的ID,然后将async设置为false将延迟执行其他web方法,直到首先执行SaveEmpData webmethod。

通过这样做,我们能够检索最后插入的ID,为其分配会话变量,将其传递给其他web方法并插入到其他表中。

此时我会做进一步的测试,似乎已经解决了这个问题。

以下是我使用异步调用的方法:

                            var data = JSON.stringify(getAllEmpData());
                            console.log(data);
                            $.ajax({
                                 url: 'testpost.asp.net/saveEmpData',
                                type: 'POST',
                                contentType: 'application/json; charset=utf-8',
                                data: JSON.stringify({ 'empdata': data }),
                                async: false,
                                success: function () {
                                    sourceComplete = true;
                                    checkComplete();
                                },
                                error: function (xhr, status, error) {
                                    alert(xhr.responseText);
                                }
                            });
                         });