【发布时间】:2017-08-02 04:07:54
【问题描述】:
我有几张桌子,其中一张叫做雇员。
它通过 EmployeeID 与其他几个表相关。
我们想将数据插入Employees表,检索最后插入的ID,然后立即将其插入另一个表,可能更多的表。
我以前做过几次。这次的不同之处在于我们使用 ajax 调用、JSON 对象和 web 方法。
将记录插入到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
【问题讨论】:
-
这听起来像是一个 sql 问题。
-
不,不是全部。我不认为你理解我的问题。我已经做过很多次了,并且有很多关于如何在 SQL 中执行此操作的在线示例。例如,使用 scope_identity 如:
SET @id=SCOPE_IDENTITY()问题可能归结为将 ID 从一个 webmethod 传递到另一个。