Hello Team,
I have some few issues with my project,
The Array is not able to send the table data rom the client side to the server side.
I want the controller to calculate taxes and profit on each individual sales and save them into the sales table.
I want to print sales receipt after sales by Transaction.
the stock table contains cost price and the selling price of the items.
function SaveSales() {
debugger;
var ObjSalesModel = {
tblSales: {
// Prepare the data
Amount: parseFloat($('#txtTotal').val()),
Discount: parseFloat($('#discountPercent').val()),
GrandTotal: parseFloat($('#grandTotal').val()),
},
SalesItems: []
};
$("#tblAppendHere").find("tr:gt(0)").each(function () {
debugger;
var SalesItem = {
StockID: parseInt($(this).find("td:eq(1)").text()),
SalesID: parseInt($(this).find("td:eq(2)").text()),
Qty: parseInt($(this).find("td:eq(3)").text()),
Rate: parseInt($(this).find("td:eq(4)").text()),
Amount: parseInt($(this).find("td:eq(5)").text())
};
ObjSalesModel.SalesItems.push(SalesItem);
});
//post data to server
$.ajax({
async: true,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "JSON",
url: "/SalesEntry/SaveSales",
data: JSON.stringify(ObjSalesModel),
success: function (data) {
if(data.message==true){
toastr.success(data.message==true"Sales process successfully!...");
// After successful save, open the print preview in a popup
var orderNumber = data.TransactionNo;
// Assuming the order number is returned from the server
var printUrl = '/SalesEntry/SalesReceipt?TransactionNo=' + orderNumber;
//window.open(printUrl, 'PrintPreview', 'width=800,height=600');
window.location = printUrl;
}
}, error: function () {
alert("There is some problem adding the data");
}
//});
//}
});
}
public ActionResult SaveSales(SalesModel ObjSalesModel)
{
if (ObjSalesModel == null || ObjSalesModel.tblSales == null)
{
return Json(new { result = false, message = "Invalid data received." }, JsonRequestBehavior.AllowGet);
}
try
{
decimal vat = Vat;
decimal costPrice = CostPrice;
decimal sellingPrice = SellingPrice;
decimal Profit = SellingPrice - CostPrice;
decimal Vatpercent = (vat / 100) * sellingPrice;
tblSale ObjSales = new tblSale();
ObjSales.OrderDate = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
ObjSales.TransactionNo = string.Format("{0:ddmmmyyyyhhmmss }", DateTime.Now);
ObjSales.Amount = ObjSalesModel.Amount;
ObjSales.Discount = ObjSalesModel.Discount;
ObjSales.Tax = ObjSalesModel.Tax;
ObjSales.GrandTotal = ObjSalesModel.GrandTotal;
ObjSales.Profit = ObjSalesModel.Profit;
ObjSales.UserID = ObjSalesModel.UserID;
objASPNETPHARMACYDBEntities.tblSales.Add(ObjSales);
objASPNETPHARMACYDBEntities.SaveChanges();
ObjSales.SalesID = ObjSalesModel.SalesID;
foreach (var sales in ObjSalesModel.SalesItems)
{
tblSalesItem ObjSalesItem = new tblSalesItem();
ObjSalesItem.StockID = ObjSalesModel.StockID;
ObjSalesItem.SalesID = ObjSalesModel.SalesID;
ObjSalesItem.Qty = ObjSalesModel.Qty;
ObjSalesItem.Rate = ObjSalesModel.Rate;
ObjSalesItem.Amount = ObjSalesModel.Amount;
objASPNETPHARMACYDBEntities.tblSalesItems.Add(ObjSalesItem);
objASPNETPHARMACYDBEntities.SaveChanges();
var ObjtblStock = objASPNETPHARMACYDBEntities.tblStocks.Where(x => x.StockID == sales.StockID).FirstOrDefault();
ObjtblStock.Qty = (ObjtblStock.Qty) - (sales.Qty);
objASPNETPHARMACYDBEntities.Entry(ObjtblStock).State = EntityState.Modified;
objASPNETPHARMACYDBEntities.SaveChanges();
}
return Json(new { result = true, message = "Sales fail to saved!" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//throw;
return Json(new { result = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
//return Json(new { result = true, message = "Sales successfully saved!" }, JsonRequestBehavior.AllowGet);
}
}

Tuhin PaulRank #7 · 71.9K reputationPosted Jan 31, 2025, 12:52 AM EST
There are several issues that need to be addressed to check the sales data is correctly sent from the client side to the server side, and that the calculations for taxes and profit are correctly performed.
1. Array Data Not Sent Correctly
The error messages indicate that the
SalesItemslist is not being accessed correctly in the server-side code. Specifically, the propertiesStockID,SalesID,Qty,Rate, andAmountare not being recognized.Solution:
Check the
SalesItemslist is correctly populated on the client side and matches the server-side model.Update the server-side code to correctly access the properties of each
SalesItemin the list.Updated Client-Side Code:
function SaveSales() { debugger; var ObjSalesModel = { tblSales: { Amount: parseFloat($('#txtTotal').val()), Discount: parseFloat($('#discountPercent').val()), GrandTotal: parseFloat($('#grandTotal').val()), }, SalesItems: [] }; $("#tblAppendHere").find("tr:gt(0)").each(function () { debugger; var SalesItem = { StockID: parseInt($(this).find("td:eq(1)").text()), SalesID: parseInt($(this).find("td:eq(2)").text()), Qty: parseInt($(this).find("td:eq(3)").text()), Rate: parseFloat($(this).find("td:eq(4)").text()), Amount: parseFloat($(this).find("td:eq(5)").text()) }; ObjSalesModel.SalesItems.push(SalesItem); }); // Post data to server $.ajax({ async: true, contentType: "application/json; charset=utf-8", type: "POST", dataType: "JSON", url: "/SalesEntry/SaveSales", data: JSON.stringify(ObjSalesModel), success: function (data) { if (data.result == true) { toastr.success("Sales process successfully!..."); var orderNumber = data.TransactionNo; var printUrl = '/SalesEntry/SalesReceipt?TransactionNo=' + orderNumber; window.location = printUrl; } }, error: function () { alert("There is some problem adding the data"); } }); }Updated Server-Side Code:
public ActionResult SaveSales(SalesModel ObjSalesModel) { if (ObjSalesModel == null || ObjSalesModel.tblSales == null) { return Json(new { result = false, message = "Invalid data received." }, JsonRequestBehavior.AllowGet); } try { decimal vat = Vat; // Assuming Vat is defined somewhere decimal costPrice = CostPrice; // Assuming CostPrice is defined somewhere decimal sellingPrice = SellingPrice; // Assuming SellingPrice is defined somewhere decimal Profit = sellingPrice - costPrice; decimal Vatpercent = (vat / 100) * sellingPrice; tblSale ObjSales = new tblSale(); ObjSales.OrderDate = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"); ObjSales.TransactionNo = string.Format("{0:ddMMMyyyyHHmmss}", DateTime.Now); ObjSales.Amount = ObjSalesModel.tblSales.Amount; ObjSales.Discount = ObjSalesModel.tblSales.Discount; ObjSales.Tax = Vatpercent; ObjSales.GrandTotal = ObjSalesModel.tblSales.GrandTotal; ObjSales.Profit = Profit; ObjSales.UserID = ObjSalesModel.UserID; objASPNETPHARMACYDBEntities.tblSales.Add(ObjSales); objASPNETPHARMACYDBEntities.SaveChanges(); foreach (var sales in ObjSalesModel.SalesItems) { tblSalesItem ObjSalesItem = new tblSalesItem(); ObjSalesItem.StockID = sales.StockID; ObjSalesItem.SalesID = ObjSales.SalesID; // Use the newly generated SalesID ObjSalesItem.Qty = sales.Qty; ObjSalesItem.Rate = sales.Rate; ObjSalesItem.Amount = sales.Amount; objASPNETPHARMACYDBEntities.tblSalesItems.Add(ObjSalesItem); objASPNETPHARMACYDBEntities.SaveChanges(); var ObjtblStock = objASPNETPHARMACYDBEntities.tblStocks.Where(x => x.StockID == sales.StockID).FirstOrDefault(); if (ObjtblStock != null) { ObjtblStock.Qty = ObjtblStock.Qty - sales.Qty; objASPNETPHARMACYDBEntities.Entry(ObjtblStock).State = EntityState.Modified; objASPNETPHARMACYDBEntities.SaveChanges(); } } return Json(new { result = true, message = "Sales successfully saved!", TransactionNo = ObjSales.TransactionNo }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { result = false, message = ex.Message }, JsonRequestBehavior.AllowGet); } }2. Calculate Taxes and Profit
The server-side code should calculate taxes and profit for each sale. Check the
CostPriceandSellingPriceare retrieved from thetblStocktable.Updated Calculation Logic:
foreach (var sales in ObjSalesModel.SalesItems) { var stockItem = objASPNETPHARMACYDBEntities.tblStocks.Where(x => x.StockID == sales.StockID).FirstOrDefault(); if (stockItem != null) { decimal costPrice = stockItem.CostPrice; decimal sellingPrice = stockItem.SellingPrice; decimal profit = sellingPrice - costPrice; decimal vatAmount = (vat / 100) * sellingPrice; // Update the sales item with calculated values sales.Amount = sellingPrice * sales.Qty; sales.Profit = profit * sales.Qty; sales.Tax = vatAmount * sales.Qty; } }4. Update the Stock Table
Check the stock table is updated correctly after each sale. The provided code already handles this, but make sure the
tblStockentity is correctly updated.hope this helps.
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 27, 2025, 12:08 PM EST
This is my JS table
var $table = $('#tblAppendHere');
$table.append(
'
//gets sales ID for name , value (for form collection) but shows stock id in the list (for UX purpose)
'
'
'
'
'
//remove icon
'
+ '
);
Vinay SinghRank #604 · 4K reputationPosted Jan 31, 2025, 1:51 PM EST
Hi,
Try the below code.
var formData = new FormData(); var x = $("#formId").serializeArray(); $.each(x, function (i, field) { formData.append(field.name, field.value); });Now you need to pass the value of "formData " in the ajax.
$.ajax({ async: true, contentType: "application/json; charset=utf-8", type: "POST", dataType: "JSON", url: "/SalesEntry/SaveSales", data: formData , success: function (data) { //---------- your code } });Herre you need yo put your and all controls and table in the form tag.
@using (Html.BeginForm("SaveSales", "SalsMaster", FormMethod.Post, new { @Id = "formnewsale", @enctype = "multipart/form-data" })) { //Yout table }make sure the model class bind should same as the controlleer end.
Thanks
Vinay(codemantra99.com)
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 28, 2025, 4:11 PM EST
Hello Team ,
Please any assistant will be highly appreciated, I'm stacked here
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 31, 2025, 4:40 PM EST
Thank you team,
I will update and revert accordingly
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Feb 1, 2025, 7:35 AM EST
Hello Mr Paul.
After updating my code with your format, this is the error message that popup on the consule panel.
Unchecked runtime.lastError: The message port closed before a response was received.