What I'm trying to do is when I select number of products from dropdown it appears in below table. Now when i click Save button below the table, I want data to be insert in two Database table i.e Sales and SaleItems. Well Data is inserting in Sales table but I don't know how to insert in another table SaleItems.
Please help me how can i do that?
Here's my code
<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);
});
</script>
$.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.");
}
});
And here's my Controller Code
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);
}
}