【发布时间】:2022-01-31 04:42:52
【问题描述】:
我正在 ASP.NET MVC 中构建一个销售点系统,我希望将包含所有订单的 HTML 表的内容保存到数据库中。 我尝试通过 JSON 将它发送到控制器,但它只保存表的第一行并忽略其余行。
此外,除了 HTML 表格内容之外,我还有一些文本框中的数据,我想将它们保存到数据库中,尽管必须首先在控制器中对其进行操作。下面是我尝试过的代码,但它只保存了表格的第一行而忽略了其他代码。
以下是Controller端代码
public JsonResult InsertOrders(List<OrderDetail> orderDetails)
{
using (POSContext entities = new POSContext())
{
//Check for NULL.
if (orderDetails == null)
{
orderDetails = new List<OrderDetail>();
}
//Loop and insert records.
foreach (OrderDetail orderDetail in orderDetails)
{
orderDetail.Order_Date = WATTime;
orderDetail.Cashier= User.Identity.Name;
entities.OrderDetails.Add(orderDetail);
}
int insertedRecords = entities.SaveChanges();
return Json(insertedRecords);
}
}
下面是我将 JSON 传递给后端的前端
///////Save Transactions To Database// Still testing this line of codes
$('#btnsavetransaction').click(function () {
//Loop through the Table rows and build a JSON array.
var orders = new Array();
$("#tblCart tbody tr").each(function () {
var row = $(this);
var order = {};
order.Item_ID = row.find("TD").eq(1).html();
order.Item_Name = row.find("TD").eq(2).html();
order.salesPrice = row.find("TD").eq(3).html();
order.Qty = row.find("TD").eq(4).html();
order.Amount = row.find("TD").eq(5).html();
orders.push(order);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Transactions/Transactions/InsertOrders",
data: JSON.stringify(orders),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
它实际上保存了第一行,但忽略了其他行。
然后,我在文本框中也有一些数据也想传递给控制器,因为我已将表格作为 JSON 传递,如何也传递文本框的值?
谢谢。
编辑:以下是完整视图
@model POS_Web.Models.POSModel.Cartdummy
@{
ViewBag.Title = "Point Of Sales";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="w3-container" style="padding-left:10px">
<div class="col-sm-1"></div>
<div class="col-sm-9 w3-card-4" style="padding-left:40px; padding-right:20px">
<h2 class="w3-center"><strong>Point Of Sales </strong></h2>
<div class="w3-row">
@using (Html.BeginForm("PointOfSales", "Transactions", new { area = "Transactions" }, FormMethod.Post, new { id = "form" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@*@Html.HiddenFor(model => model.Id)*@
@*@Html.HiddenFor(model => model.New_Quantity)*@
<div class="w3-responsive w3-row">
@*<h2 class="w3-center"><strong>All Items in Stock </strong></h2>*@
<table id="tblItems" class="table w3-table-all w3-hoverable">
<thead>
<tr>
<th>Item ID</th>
<th>Item Category</th>
<th>Item Name</th>
<th>Cost Price</th>
<th>Sales Price</th>
<th>Quantity</th>
<th>Reorder Level</th>
<th>Item Discontinued?</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="w3-row">
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Item_ID, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Item_ID, new { htmlAttributes = new { placeholder = "Item ID", @class = "form-control", @readonly = "true" } })
@Html.ValidationMessageFor(model => model.Item_ID, "", new { @class = "text-danger" })
</div>
</div>
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Item_Name, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Item_Name, new { htmlAttributes = new { placeholder = "Item Name", @class = "form-control", @readonly = "true" } })
@Html.ValidationMessageFor(model => model.Item_Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Sales_Price, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Sales_Price, new { htmlAttributes = new { placeholder = "Price", @class = "form-control", @readonly = "true" } })
@Html.ValidationMessageFor(model => model.Sales_Price, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="w3-row">
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Qty, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Qty, new { htmlAttributes = new { placeholder = "Qty", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Qty, "", new { @class = "text-danger" })
</div>
</div>
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Amount, new { htmlAttributes = new { placeholder = "Amount", @class = "form-control", @readonly = "true" } })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
<div class="w3-col w3-third">
<div class="form-group">
<input type="button" id="btnAddToCart" value="Add To Cart" class="btn btn-primary btn-block" />
</div>
</div>
</div>
<div class="w3-row">
<h3 class="w3-center"><strong>Shopping Cart </strong></h3>
</div>
<div class="w3-responsive w3-row">
<table id="tblCart" class="table w3-table-all">
<thead>
<tr>
<th>Remove From Cart</th>
<th>Item ID</th>
<th>Item Name</th>
<th>Sales Price</th>
<th>Qty</th>
<th>Amount</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="w3-col w3-third">
</div>
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Total_Amount, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Total_Amount, new { htmlAttributes = new { placeholder = "Total Amount", @class = "form-control", @readonly = "True" } })
@Html.ValidationMessageFor(model => model.Total_Amount, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Amount_Tendered, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Amount_Tendered, new { htmlAttributes = new { placeholder = "Amount Tendered", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Amount_Tendered, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Change_Received, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Change_Received, new { htmlAttributes = new { placeholder = "Change Received", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Change_Received, "", new { @class = "text-danger" })
</div>
</div>
<div class="w3-col w3-third">
<div class="form-group">
@Html.LabelFor(model => model.Payment_Method, htmlAttributes: new { @class = "control-label" })
@Html.DropDownList("Payment_Method", new List<SelectListItem>{
new SelectListItem{ Text="Cash", Value="Cash"},
new SelectListItem{ Text="Bank Transfer", Value="Bank Transfer"},
new SelectListItem{ Text="POS", Value="POS"}
}, "--- Select Payment Method ---", new { @class = "form-control" }
)
@Html.ValidationMessageFor(model => model.Payment_Method, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Customer_ID, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Customer_ID, new { htmlAttributes = new { placeholder = "Customer ID", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Customer_ID, "", new { @class = "text-danger" })
</div>
<br />
<div class="form-group">
<input type="submit" value="Save" class="btn btn-success btn-block" id="submitbtn" />
</div>
<div class="form-group">
<input type="button" id="btnsavetransaction" value="Save Transaction" class="btn btn-primary btn-block" />
</div>
</div>
<hr />
</div>
}
</div>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/jquery.validate.js")
@Scripts.Render("~/Scripts/jquery.validate.date.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
@*<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>*@
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script type="text/javascript">
//Declaring the Total Amount First
var totalAmount = 0;
var itemDiscontinued = null;
var stock = 0;
$(document).ready(function () {
$('#submitbtn').click(function (e) {
$('#errorWithdraw').css('display', 'none');
if (!$('#form').valid()) {
alert('Some Input Fields has Not Been Filled Correctly');
return false;
} else if ($('#form').valid()) {
var x = confirm("Are you sure to Save this Transaction?"); //confirm text
if (x == true) { //checking whether user clicked ok or cancel
$('.spinner').css('display', 'block'); //if clicked ok spinner shown)
} else { //else if clicked cancel spinner is hidden
$('.spinner').css('display', 'none');
return false //stops further process
}
}
});
//Table listing all categories and allows filtering
$(function () {
var oTable;
$.ajax({
type: "POST",
url: "/StockManagement/StockManagement/Items",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var customers = eval(response);
oTable = $("#tblItems").DataTable({
bLengthChange: true,
lengthMenu: [[5], [5]],
bFilter: true,
bSort: true,
bPaginate: true,
data: customers,
columns: [
{ 'data': 'Item_ID' },
{ 'data': 'Item_category' },
{ 'data': 'Item_Name' },
{ 'data': 'Cost_Price' },
{ 'data': 'Sales_Price' },
{ 'data': 'Quantity' },
{ 'data': 'Reorder_Level' },
{ 'data': 'Item_Discontinued' },
]
});
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
$('#Item_Name').keyup(function () {
oTable.search($(this).val()).draw();
})
});
//Making the Table clickable
$(function () {
$('#tblItems').on('click', 'tr', function () {
var currentRow = $(this).closest("tr");
var itemID = currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var itemName = currentRow.find("td:eq(2)").text(); // get current row 2nd TD
// var oldQty = currentRow.find("td:eq(5)").text(); // get current row 5th TD
var salesprice = currentRow.find("td:eq(4)").text(); // get current row 5th TD
itemDiscontinued = currentRow.find("td:eq(7)").text(); // getting the Discontinued status of the item selected
stock = currentRow.find("td:eq(5)").text(); // getting the Stock of the Item selected
$('#Item_ID').val(itemID);
$('#Item_Name').val(itemName);
// $('#Old_Quantity').val(oldQty);
$('#Sales_Price').val(salesprice);
});
});
//The Cart table Jquery
$(function () {
//calculating the Amount when Qty is entered
$('#Qty').keyup(function () {
var Qty = $('#Qty').val();
if ($('#Item_ID').val() == '' || $('#Item_ID').val() == undefined) {
alert('Please Select an Item First');
$('#Qty').val('');
return false;
}
var salesPrice = parseFloat($('#Sales_Price').val());
var amount = Qty * salesPrice;
$('#Amount').val(amount);
})
});
//Jquery for the AddToCart Button
$('#btnAddToCart').click(function () {
var itemID = $('#Item_ID').val();
var itemName = $('#Item_Name').val();
var salesprice = parseFloat($('#Sales_Price').val());
var Qty = $('#Qty').val();
var amount = $('#Amount').val();
var newstock = stock - Qty;
if ($('#Item_ID').val() == '' || $('#Item_ID').val() == undefined) {
alert('Please Select an Item to Add to Cart');
return false;
}
if ($('#Qty').val() == '' || $('#Qty').val() == undefined || $('#Qty').val() == 0) {
alert('Please Enter the Qty of The Item Been Purchased');
return false;
}
if ($('#Sales_Price').val() == '' || $('#Sales_Price').val() == undefined || $('#Sales_Price').val() == 0) {
alert('Please Enter the Qty of The Item Been Purchased');
return false;
}
if (itemDiscontinued == 'Yes' ) {
alert('The Item Selected has been Discontinued and cannot be sold');
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#Sales_Price').val('');
$('#Qty').val('');
$('#Amount').val('');
return false;
}
if (newstock < 0) {
alert('The Qty of ' + $('#Item_Name').val() + ' Selected to be purchased is more than what is in store, Please replenish item');
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#Sales_Price').val('');
$('#Qty').val('');
$('#Amount').val('');
return false;
}
//Check if the Item is already in Cart////////////////////////////
var $tds = $('#tblCart tr > td:nth-child(2)').filter(function () {
return $.trim($(this).text()) == itemID;
});
if ($tds.length != 0) {
alert("Item already in Cart");
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#Sales_Price').val('');
$('#Qty').val('');
$('#Amount').val('');
return false;
}
/////////////////////////////////////////////////////////////////////
//Bild up the table row
var table =
"<tr>" +
"<td><button type='button' name='record' class='btn btn-danger' onclick='deleterow(this)'> Remove </td>" +
"<td>" + itemID + "</td>" +
"<td>" + itemName + "</td>" +
"<td>" + salesprice + "</td>" +
"<td>" + Qty + "</td>" +
"<td>" + amount + "</td>" +
"<tr>";
totalAmount += Number(amount);
$('#Total_Amount').val(totalAmount);
$('#tblCart tbody').append(table);
//Empty the Textboxes to allow for new item
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#Sales_Price').val('');
$('#Qty').val('');
$('#Amount').val('');
});
///////Save Transactions To Database// Still testing this line of codes
$('#btnsavetransaction').click(function () {
//Loop through the Table rows and build a JSON array.
var orders = new Array();
$("#tblCart tbody tr").each(function () {
var row = $(this);
var order = {};
order.Item_ID = row.find("TD").eq(1).html();
order.Item_Name = row.find("TD").eq(2).html();
order.salesPrice = row.find("TD").eq(3).html();
order.Qty = row.find("TD").eq(4).html();
order.Amount = row.find("TD").eq(5).html();
orders.push(order);
});
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Transactions/Transactions/InsertOrders",
//data: JSON.stringify(orders),
data: JSON.stringify({ orderDetails: orders }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
});
////Function to Delete Row from Cart
function deleterow(e) {
var amount = parseFloat($(e).parent().parent().find('td:last').text(), 10);
totalAmount -= amount;
$('#Total_Amount').val(totalAmount);
$(e).parent().parent().remove();
}
function showSpinner() {
$('.spinner').css('display', 'block'); //if clicked ok spinner shown
}
</script>
}
【问题讨论】:
-
签入InsertOrders,你得到订单详情列表吗?
-
您要么必须将每个订单详细信息对象保存在 foreach 中,要么在对象列表上添加范围并立即添加它们。
-
@urlreader,我断点了代码,但它只有一行被传递给控制器。
-
@GHDevOps,我在 foreach 中所做的是互相保存细节。还是我做错了?
-
如果只有一行进来,那么它就是你的字符串化。在 MVC 中执行此操作的最简单方法是使用带有提交按钮的表单。这样你的模型就会自动序列化回控制器。如果您需要执行 ajax,请在 jQuery 中连接提交表单操作,防止默认设置,然后使用 ajax 回发。您的 $(this) 引用应该更容易传回服务器。
标签: javascript c# jquery ajax asp.net-mvc