将 html table 的值保存到 ASP NET MVC 和 JQUERY/AJAX 中的数据库
Saving values of html table to database in ASP NET MVC and JQUERY/AJAX
我正在 ASP.NET MVC 中构建一个销售点系统,我希望将包含所有订单的 HTML table 的内容保存到数据库中。
我尝试通过 JSON 将其发送到控制器,但它仅保存 table 的第一行并忽略其余行。
此外,除了 HTML table 内容外,我在文本框中也有一些数据,我想将它们保存到数据库中,但必须先在控制器中对其进行操作。下面是我试过的代码,但它只保存 table 的第一行并忽略其他行。
下面是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.");
}
});
});
它实际上保存了第一行但忽略了其他行。
然后,我在文本框中也有一些数据也想传递给控制器,因为我已经将 table 作为 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>
}
// jQuery for the AddToCart Button
$('#btnAddToCart').click(function () {
var itemID = $('#Item_ID').val();
var itemName = $('#Item_Name').val();
var salesprice = parseFloat($('#salesPrice').val()).toFixed(2);
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 ($('#salesPrice').val() == '' || $('#salesPrice').val() == undefined || $('#salesPrice').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('');
$('#salesPrice').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('');
$('#salesPrice').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('');
$('#salesPrice').val('');
$('#Qty').val('');
$('#Amount').val('');
return false;
}
// Build up the table row
var tbody = $('#tblCart tbody');
var tr = $('<tr></tr>');
tr.append("'<td><button type='button' name='record' class='btn btn-danger' onclick='deleterow(this)'> Remove </td>'")
tr.append('<td>' + itemID + '</td>');
tr.append('<td>' + itemName + '</td>');
tr.append('<td>' + salesprice + '</td>');
tr.append('<td>' + Qty + '</td>');
tr.append('<td>' + amount + '</td>');
tbody.append(tr);
totalAmount += Number(amount);
$('#Total_Amount').val(parseFloat(totalAmount).toFixed(2));
// Empty the Textboxes to allow for new item
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#salesPrice').val('');
$('#Qty').val('');
$('#Amount').val('');
});
// Checkout and Save Transactions To Database
$('#btnCheckOut').click(function() {
// First check if the TableCart is not empty
if ($('#tblCart tr').length <= 1) {
alert('The Cart is Empty, Please add Items to Cart');
return false;
}
if ($('#Amount_Tendered').val() == '' || $('#Amount_Tendered').val() == undefined || $('#Amount_Tendered').val() <= 0) {
alert('Please Enter the Amount Tendered by Customer');
return false;
}
if ($('#Payment_Method').val() == '' || $('#Payment_Method').val() == undefined) {
alert('Please Select the Payment Method');
return false;
}
var totalAmount = parseFloat($('#Total_Amount').val());
var changeReceived = parseFloat($('#Change_Received').val());
if (changeReceived < 0 ) {
alert('The Amount Tendered Cannot be Less than Total Amount');
return false;
}
finalPayment(); //Call the finalpayment method
EmptyControls(); //Calling the Empty control mehod
loaddata(); //Items to be reloaded
});
// 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 to send cart table to controller
function finalPayment() {
var totalAmount = $('#Total_Amount').val();
var paymentMethod = $('#Payment_Method').val();
var amountTendered = $('#Amount_Tendered').val();
var changeReceived = $('#Change_Received').val();
var customerID = $('#Customer_ID').val();
var orderdetails = new Array();
$('#tblCart tr:not(:first)').each(function() {
var row = $(this);
var orderdetail = {};
orderdetail.Item_ID = row.find("TD").eq(1).html();
orderdetail.Item_Name = row.find("TD").eq(2).html();
orderdetail.salesPrice = row.find("TD").eq(3).html();
orderdetail.Qty = row.find("TD").eq(4).html();
orderdetail.Amount = row.find("TD").eq(5).html();
orderdetails.push(orderdetail);
});
$.ajax({
async: true,
type: "POST",
url: "/Transactions/Transactions/InsertOrders",
//data: JSON.stringify(orderdetails),
data: JSON.stringify({
orderdetails: orderdetails,
totalAmount: totalAmount,
paymentMethod: paymentMethod,
amountTendered: amountTendered,
changeReceived: changeReceived,
customerID: customerID
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Something went wrong, processing not completed");
}
});
}
我正在 ASP.NET MVC 中构建一个销售点系统,我希望将包含所有订单的 HTML table 的内容保存到数据库中。 我尝试通过 JSON 将其发送到控制器,但它仅保存 table 的第一行并忽略其余行。
此外,除了 HTML table 内容外,我在文本框中也有一些数据,我想将它们保存到数据库中,但必须先在控制器中对其进行操作。下面是我试过的代码,但它只保存 table 的第一行并忽略其他行。
下面是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.");
}
});
});
它实际上保存了第一行但忽略了其他行。
然后,我在文本框中也有一些数据也想传递给控制器,因为我已经将 table 作为 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>
}
// jQuery for the AddToCart Button
$('#btnAddToCart').click(function () {
var itemID = $('#Item_ID').val();
var itemName = $('#Item_Name').val();
var salesprice = parseFloat($('#salesPrice').val()).toFixed(2);
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 ($('#salesPrice').val() == '' || $('#salesPrice').val() == undefined || $('#salesPrice').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('');
$('#salesPrice').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('');
$('#salesPrice').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('');
$('#salesPrice').val('');
$('#Qty').val('');
$('#Amount').val('');
return false;
}
// Build up the table row
var tbody = $('#tblCart tbody');
var tr = $('<tr></tr>');
tr.append("'<td><button type='button' name='record' class='btn btn-danger' onclick='deleterow(this)'> Remove </td>'")
tr.append('<td>' + itemID + '</td>');
tr.append('<td>' + itemName + '</td>');
tr.append('<td>' + salesprice + '</td>');
tr.append('<td>' + Qty + '</td>');
tr.append('<td>' + amount + '</td>');
tbody.append(tr);
totalAmount += Number(amount);
$('#Total_Amount').val(parseFloat(totalAmount).toFixed(2));
// Empty the Textboxes to allow for new item
$('#Item_ID').val('');
$('#Item_Name').val('');
$('#salesPrice').val('');
$('#Qty').val('');
$('#Amount').val('');
});
// Checkout and Save Transactions To Database
$('#btnCheckOut').click(function() {
// First check if the TableCart is not empty
if ($('#tblCart tr').length <= 1) {
alert('The Cart is Empty, Please add Items to Cart');
return false;
}
if ($('#Amount_Tendered').val() == '' || $('#Amount_Tendered').val() == undefined || $('#Amount_Tendered').val() <= 0) {
alert('Please Enter the Amount Tendered by Customer');
return false;
}
if ($('#Payment_Method').val() == '' || $('#Payment_Method').val() == undefined) {
alert('Please Select the Payment Method');
return false;
}
var totalAmount = parseFloat($('#Total_Amount').val());
var changeReceived = parseFloat($('#Change_Received').val());
if (changeReceived < 0 ) {
alert('The Amount Tendered Cannot be Less than Total Amount');
return false;
}
finalPayment(); //Call the finalpayment method
EmptyControls(); //Calling the Empty control mehod
loaddata(); //Items to be reloaded
});
// 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 to send cart table to controller
function finalPayment() {
var totalAmount = $('#Total_Amount').val();
var paymentMethod = $('#Payment_Method').val();
var amountTendered = $('#Amount_Tendered').val();
var changeReceived = $('#Change_Received').val();
var customerID = $('#Customer_ID').val();
var orderdetails = new Array();
$('#tblCart tr:not(:first)').each(function() {
var row = $(this);
var orderdetail = {};
orderdetail.Item_ID = row.find("TD").eq(1).html();
orderdetail.Item_Name = row.find("TD").eq(2).html();
orderdetail.salesPrice = row.find("TD").eq(3).html();
orderdetail.Qty = row.find("TD").eq(4).html();
orderdetail.Amount = row.find("TD").eq(5).html();
orderdetails.push(orderdetail);
});
$.ajax({
async: true,
type: "POST",
url: "/Transactions/Transactions/InsertOrders",
//data: JSON.stringify(orderdetails),
data: JSON.stringify({
orderdetails: orderdetails,
totalAmount: totalAmount,
paymentMethod: paymentMethod,
amountTendered: amountTendered,
changeReceived: changeReceived,
customerID: customerID
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Something went wrong, processing not completed");
}
});
}