如何解决通过表tbody将数据插入两个数据库表
我要尝试的是从下拉列表中选择产品数量时,它显示在下表中。现在,当我单击表格下方的保存按钮时,我希望将数据插入两个数据库表格中,即Sales和SaleItems。 数据正在Sales表中插入,但我不知道如何在另一个表SaleItems中插入。 请帮我怎么做?
这是我的代码
<table id="table" class="table">
<thead>
<tr>
<th scope="col">Product Id</th>
<th scope="col">Company</th>
<th scope="col">Product Name</th>
<th scope="col">User Name</th>
<th scope="col">User Mobile</th>
<th scope="col">Price per product</th>
<th scope="col">Quantity</th>
<th scope="col">Total Price</th>
</tr>
</thead>
<tbody></tbody>
<tfoot><tr><td colspan="2">Grand Total : </td><td id="GrandTotal"></td></tr></tfoot>
</table>
<script>
$('#productSelect').change(function () {
var id = $(this).val();
if (id > 0) {
$.get("GetProduct",{ productId: id },function (result) {
console.log(result)
$("tbody").append("<tr><td>" + result.ProductId + "</td><td>" + result.CompanyName + "</td><td>" + result.ProductName + "</td><td>" + result.UserName + "</td><td>" + result.UserMobile + "</td><td>" + result.ProductPrice + "</td><td><button type='button' class='btn btn-primary' onClick='subtract(" + id + "," + result.ProductPrice + ")'>-</button><button type='button' class='btn btn-dark' id='" + id + "' value='0'>0</button><button type='button' class='btn btn-primary' onClick='add(" + id + "," + result.ProductPrice + ")'>+</button></td><td id='sum" + id + "'>0</td><td><a onclick='removeRow(this)'>x</a></td></tr>")
CalculateGrandTotal();
});
}
})
$("body").on("click","#btnSave",function () {
//Loop through the Table rows and build a JSON array.
var sales = new Array();
$(".table tbody tr").each(function () {
var row = $(this);
var Sale = {};
Sale.UserName = row.find("td").eq(3).html();
Sale.UserMobile = row.find("td").eq(4).html();
Sale.NetTotal = row.find("td").eq(8).html();
Sale.ProductQuantity = row.find("td").eq(5).val();
sales.push(Sale);
});
$.ajax({
type: "POST",url: "/Product/Insertsales",data: JSON.stringify(sales),contentType: "application/json; charset=utf-8",dataType: "json",success: function (r) {
alert(r + " records inserted.");
}
});
</script>
这是我的控制器代码
public JsonResult InsertSales(List<Sale> sales)
{
using (sampledb6Entities sampledb6Entities = new sampledb6Entities())
{
//Truncate Table to delete all old records.
//sampledb6Entities.Database.ExecutesqlCommand("TruncATE TABLE [Sales]");
//Check for NULL.
if (sales == null)
{
sales = new List<Sale>();
}
//Loop and insert records.
foreach (Sale sale in sales)
{
sampledb6Entities.Sales.Add(sale);
}
int insertedRecords = sampledb6Entities.SaveChanges();
return Json(insertedRecords);
}
}
解决方法
您应该使用Sale对象创建SaleItem对象并将其插入表格中
foreach (Sale sale in sales)
{
sampledb6Entities.Sales.Add(sale);
SaleItem saleItem = ... // convert the sale to SaleItem object
sampledb6Entities.SaleItems.Add(saleItem);
}
int insertedRecords = sampledb6Entities.SaveChanges();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。