Hello Team,
My Ajax POST request fails to post data to the controller. I put a debugger into the javascript function, and it loads all the data correctly but is not able to post them to the controller and to the databse.
C#
$('#btnAdd').on('click', function () {
//jQuery Validations
var isValidation = true;
if (purchaseItems.length == 0) {
isAllValid = false;
alert('Please Add items to purchase!');
}
if ($('#SelectSupplier').val() == "0") {
isAllValid = false;
$('#SelectSupplier').siblings('span.error').css('visibility', 'visible');
}
else {
$('#SelectSupplier').siblings('span.error').css('visibility', 'hidden');
}
if (isValidation) {
purchaseItems.push({
ItemID: $('#selectItem').val(),
ItemName: $('#selectItem option:selected').text(),
Batch: $('#Batch').val(),
Qty: $('#Qty').val(),
CostPrice: $('#CP').val(),
SellingPrice: $('#SP').val(),
Expiry: $('#Expiry').val(),
PurchaseID: $('#PurchaseID').val() + ' / ' + $('#SelectSupplier').val(),
BonusIncluded: 0
});
$('#selectItem').val('0').focus();
$('#Batch, #Qty, #CP, #SP, #Expiry').val('');
}
GeneratedItemsTable();
});
$('#btnSubmit').on('click', function () {
var isAllValid = true;
if (purchaseItems.length == 0) {
isAllValid = false;
alert('Please Add items to purchase!');
}
if ($('#SelectSupplier').val() == "0") {
isAllValid = false;
$('#SelectSupplier').siblings('span.error').css('visibility', 'visible');
}
else {
$('#SelectSupplier').siblings('span.error').css('visibility', 'hidden');
}
if ($('#PurchaseID').val().trim() == '') {
isAllValid = false;
$('#PurchaseID').siblings('span.error').css('visibility', 'visible');
}
else {
$('#PurchaseID').siblings('span.error').css('visibility', 'hidden');
}
if ($('#InvocingDate').val() == '') {
isAllValid = false;
$('#InvocingDate').siblings('span.error').css('visibility', 'visible');
}
else {
$('#InvocingDate').siblings('span.error').css('visibility', 'hidden');
}
if ($('#Amount').val() == '' || isNaN($('#Amount').val())) {
isAllValid = false;
$('#Amount').siblings('span.error').css('visibility', 'visible');
}
else {
$('#Amount').siblings('span.error').css('visibility', 'hidden');
}
if (isNaN($('#Discount').val())) {
$('#Discount').siblings('span.error').css('visibility', 'visible');
}
if (isNaN($('#Tax').val())) {
$('#Tax').siblings('span.error').css('visibility', 'visible');
}
if (isAllValid) {
var purchaseModel =
{
PurchaseID: $.trim($('#PurchaseID').val() + '--' + $('#SelectSupplier').val()),
Date: $('#InvocingDate').val().trim(),
SupplierID: $('#SelectSupplier').val(),
Amount: $('#Amount').val(),
Discount: $('#Discount').val(),
Tax: $('#Tax').val(),
GrandTotal: $('#GrandTotal').val(),
IsPaid: $('#Payment').is(":checked") ? 1 : 0,
Description: $('#Description').val(),
PurchaseItems: purchaseItems
}
$(this).val('Please wait...');
//post data to server
$.ajax({
url: '@Url.Action("SavePurchase", "PurchaseEntry")',
type: "POST",
dataType: "JSON",
contentType: "application/json; chasert=utf-8",
data: JSON.stringify({ purchaseModel: purchaseModel }),
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
location.reload(true);
//clear form
purchaseItems = [];
$('#PurchaseID').val('');
$('#InvocingDate').val('');
$('#SelectSupplier').val('0');
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#btnSubmit').val('Save');
}
});
}
});
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 17, 2025, 1:22 PM EST
The way you are binding the values inside the
eachloop is problematic. You should collect the values from the table dynamically (i.e., for each row) and push them to an array. The current implementation seems to overwrite thePurchaseItemModelin each iteration, which would mean only the last row is sent to the server.And also I think you are assigning
purchaseModelto thetblPurchaseItemfield ofPurchaseItemModel, but it’s not being collected in the finalpurchaseModelobject that’s sent via the AJAX request.Amira BedhiafiRank #601 · 4K reputationPosted Jan 15, 2025, 7:06 PM EST
The
contentTypeis set as"application/json; chasert=utf-8", but it seems there is a typo (chasertinstead ofcharset).Also I ghave a sdoubt about the server-side action method not being able to accept the incoming JSON object because the parameter in the
SavePurchaseaction should match the JSON structure.[HttpPost] public JsonResult SavePurchase(PurchaseModel purchaseModel) { // put here your locig to save data return Json(new { status = true }); }Another thought, did you verify if the CORS is enabled on the serve ?
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 16, 2025, 1:57 AM EST
Thank you Amira Bedhiafi for your response.
I have corrected but it is still not working.
the is my server-side action method
public ActionResult SavePurchase(PurchaseItem purchaseModel)
{
var result = false;
try
{
tblPurchase objPurchase = new tblPurchase();();
if (purchaseModel.PurchaseID > 0)
{
objPurchase = objASPNETPHARMACYDBEntities.tblPurchases.Where(x => x.PurchaseID == purchaseModel.PurchaseID).FirstOrDefault
}
objPurchase.Date = purchaseModel.Purchase.Date;
objPurchase.SupplierID = purchaseModel.Purchase.SupplierID;
objPurchase.Amount = purchaseModel.Purchase.Amount;
objPurchase.Discount = purchaseModel.Purchase.Discount;
objPurchase.Tax = purchaseModel.Purchase.Tax;
objPurchase.GrandTotal = purchaseModel.Purchase.GrandTotal;
objPurchase.IsPaid = purchaseModel.Purchase.IsPaid;
objPurchase.Description = purchaseModel.Purchase.Description;
objASPNETPHARMACYDBEntities.SaveChanges();
purchaseModel.PurchaseID = purchaseModel.PurchaseID;
tblPurchaseItem updatePurchase = new tblPurchaseItem();();
if (purchaseModel.PurchaseItemID > 0)
{
updatePurchase = objASPNETPHARMACYDBEntities.tblPurchaseItems.Where(x => x.PurchaseItemID == purchaseModel.PurchaseItemID).FirstOrDefault
}
else
{
updatePurchase.PurchaseID = purchaseModel.PurchaseID;
updatePurchase.ItemID = purchaseModel.ItemID;
updatePurchase.Batch = purchaseModel.Batch;
updatePurchase.Qty = purchaseModel.Qty;
updatePurchase.CostPrice = purchaseModel.CostPrice;
updatePurchase.SellingPrice = purchaseModel.SellingPrice;
updatePurchase.Expiry = purchaseModel.Expiry;
objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(updatePurchase);
}
if (purchaseModel.PurchaseItemID <= 0)
{
objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(updatePurchase);
}
objASPNETPHARMACYDBEntities.SaveChanges();
result = true;
}
catch (Exception)
{
return Json(new { result = true, message = "Purchase fails to save!" }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = true, message = "Purchase successfully saved!" }, JsonRequestBehavior.AllowGet);
}
Amira BedhiafiRank #601 · 4K reputationPosted Jan 16, 2025, 7:25 AM EST
Can you please detail more your input and your expected output ?
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 16, 2025, 6:46 PM EST
Hello Team,
Any help will be highly appreciated.
Thanks
Sreenath KappoorRank #655 · 3.7K reputationPosted Jan 16, 2025, 11:19 PM EST
Hi Emmanual,
Can you please change and check this - the url as url: '/PurchaseEntry/SavePurchase' and data as, data: JSON.stringify(purchaseModel).
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 17, 2025, 1:15 AM EST
Hello Sreenath Kappoor
I change it, and when I tried saving the data, the error message that came is localhost:10435 says failed,
the function is not able to post data to the controller
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 17, 2025, 6:56 AM EST
Hello Team,
This is my revise code, and as at now the textboxes data is reaching the controller but the table data is not reaching the controller.
function SavePurchases()
{
debugger;
var tblPurchaseItem = [];
var purchaseModel = new Object();
purchaseModel.PurchaseID = $.trim($('#PurchaseID').val() + '--' + $('#SelectSupplier').val()),
purchaseModel.Date = $('#InvocingDate').val().trim(),
purchaseModel.SupplierID = $('#SelectSupplier').val(),
purchaseModel.Amount = $('#Amount').val(),
purchaseModel.Discount = $('#Discount').val(),
purchaseModel.Tax = $('#Tax').val(),
purchaseModel.GrandTotal = $('#GrandTotal').val(),
purchaseModel.IsPaid = $('#Payment').is(":checked") ? 1 : 0,
purchaseModel.Description = $('#Description').val(),
PurchaseItemModel = new Object();
$("#orderItems").find("tr:gt(0)").each(function () {
PurchaseItemModel.ItemID = $('#selectItem').val(),
PurchaseItemModel.ItemName = $('#selectItem option:selected').text(),
PurchaseItemModel.Batch = $('#Batch').val(),
PurchaseItemModel.Qty = $('#Qty').val(),
PurchaseItemModel.CostPrice = $('#CP').val(),
PurchaseItemModel.SellingPrice = $('#SP').val(),
PurchaseItemModel.Expiry = $('#Expiry').val(),
PurchaseItemModel.PurchaseID = $('#PurchaseID').val() + ' / ' + $('#SelectSupplier').val(),
PurchaseItemModel.BonusIncluded = 0
PurchaseItemModel.tblPurchaseItem = purchaseModel
var data=JSON.stringify({
purchaseModel:purchaseModel
});
//post data to server
$.ajax({
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "JSON",
url: "/PurchaseEntry/SavePurchase",
//data: JSON.stringify(purchaseModel),
data:data,
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
location.reload(true);
//clear form
purchaseItems = [];
$('#PurchaseID').val('');
$('#InvocingDate').val('');
$('#SelectSupplier').val('0');
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#btnSubmit').val('Save');
}
});
})
Table
function GeneratedItemsTable() {
if (purchaseItems.length > 0) {
var $table = $('
$table.append('
var $tbody = $('');
// var $table = $('.tableList');
');// var $tbody = $('
$.each(purchaseItems, function (i, val) {
var $row = $('
//$row.append($('
$row.append($('
$row.append($('
$row.append($('
$row.append($('
$row.append($('
$row.append($('
$row.append($('
$tbody.append($row);
});
$table.append($tbody);
$('#orderItems').html($table);
}
else {
alert("List is empty !");
}
}
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 17, 2025, 1:19 PM EST
If you are expecting
purchaseModel.tblPurchaseItemon the server side,[HttpPost] public JsonResult SavePurchase(PurchaseModel purchaseModel) { try { // Process the purchase model and its items var purchaseId = purchaseModel.PurchaseID; var purchaseItems = purchaseModel.tblPurchaseItem; // Perform the necessary database operations here return Json(new { status = true }); } catch (Exception ex) { return Json(new { status = false, message = ex.Message }); } }Also check that your model binding works correctly on the server-side and that the
PurchaseModelclass has a property fortblPurchaseItemof typeListor something similar.In your
GeneratedItemsTablefunction, the issue might be that the input fields (e.g.,#selectItem,#Batch,#Qty) inside the table rows are not being populated correctly.Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 17, 2025, 2:01 PM EST
Hello Mr Paul, initially that was how I wrote the severside method in the controller but it didn't work so I had to change it to current revise code I posted here, but with your explanation if can you remodified it for me I will be grateful
And with the JavaScript function I will check it again.
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 18, 2025, 6:18 AM EST
Hello Tuhin Paul
This is my current revise code, but the Ajax post request is not able to data in the table to the controller.
function SavePurchases()
{
debugger;
var purchaseModel = {};
var ListOfPurchaseItemsViewModel = new Array();
purchaseModel.PurchaseID = $.trim($('#PurchaseID').val() + '--' + $('#SelectSupplier').val()),
purchaseModel.Date = $('#InvocingDate').val().trim(),
purchaseModel.SupplierID = $('#SelectSupplier').val(),
purchaseModel.Amount = $('#Amount').val(),
purchaseModel.Discount = $('#Discount').val(),
purchaseModel.Tax = $('#Tax').val(),
purchaseModel.GrandTotal = $('#GrandTotal').val(),
purchaseModel.IsPaid = $('#Payment').is(":checked") ? 1 : 0,
purchaseModel.Description = $('#Description').val(),
$("#orderItems").find("tr:gt(0)").each(function () {
var PurchaseItemModel = {};
PurchaseItemModel.ItemID = $('#selectItem').val(),
PurchaseItemModel.ItemName = $('#selectItem option:selected').text(),
PurchaseItemModel.Batch = $('#Batch').val(),
PurchaseItemModel.Qty = $('#Qty').val(),
PurchaseItemModel.CostPrice = $('#CP').val(),
PurchaseItemModel.SellingPrice = $('#SP').val(),
PurchaseItemModel.Expiry = $('#Expiry').val(),
PurchaseItemModel.PurchaseID = $('#PurchaseID').val() + ' / ' + $('#SelectSupplier').val(),
PurchaseItemModel.BonusIncluded = 0
ListOfPurchaseItemsViewModel.push(PurchaseItemModel);
});
purchaseModel.ListOfPurchaseItemsViewModel = ListOfPurchaseItemsViewModel;
//post data to server
$.ajax({
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "JSON",
url: "/PurchaseEntry/SavePurchase",
data: JSON.stringify(purchaseModel),
//data:data,
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
location.reload(true);
//clear form
purchaseItems = [];
$('#PurchaseID').val('');
$('#InvocingDate').val('');
$('#SelectSupplier').val('0');
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#btnSubmit').val('Save');
}
});
}
public ActionResult SavePurchase(PurchaseItem purchaseModel)
{
var result = false;
try
{
tblPurchase objPurchase = new tblPurchase();();
if (purchaseModel.PurchaseID > 0)
{
objPurchase = objASPNETPHARMACYDBEntities.tblPurchases.Where(x => x.PurchaseID == purchaseModel.tblPurchase.PurchaseID).FirstOrDefault
}
objPurchase.Date = purchaseModel.tblPurchase.Date;
objPurchase.SupplierID = purchaseModel.tblPurchase.SupplierID;
objPurchase.Amount = purchaseModel.tblPurchase.Amount;
objPurchase.Discount = purchaseModel.tblPurchase.Discount;
objPurchase.Tax = purchaseModel.tblPurchase.Tax;
objPurchase.GrandTotal = purchaseModel.tblPurchase.GrandTotal;
objPurchase.IsPaid = purchaseModel.tblPurchase.IsPaid;
objPurchase.Description = purchaseModel.tblPurchase.Description;
objASPNETPHARMACYDBEntities.SaveChanges();
purchaseModel.PurchaseID = purchaseModel.tblPurchase.PurchaseID;
tblPurchaseItem updatePurchase = new tblPurchaseItem();();
if (purchaseModel.PurchaseItemID > 0)
{
updatePurchase = objASPNETPHARMACYDBEntities.tblPurchaseItems.Where(x => x.PurchaseItemID == purchaseModel.PurchaseItemID).FirstOrDefault
}
else
{
updatePurchase.PurchaseID = purchaseModel.PurchaseID;
updatePurchase.ItemID = purchaseModel.ItemID;
updatePurchase.Batch = purchaseModel.Batch;
updatePurchase.Qty = purchaseModel.Qty;
updatePurchase.CostPrice = purchaseModel.CostPrice;
updatePurchase.SellingPrice = purchaseModel.SellingPrice;
updatePurchase.Expiry = purchaseModel.Expiry;
objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(updatePurchase);
}
if (purchaseModel.PurchaseItemID <= 0)
{
objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(updatePurchase);
}
objASPNETPHARMACYDBEntities.SaveChanges();
result = true;
}
catch (Exception)
{
return Json(new { result = true, message = "Purchase fails to save!" }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = true, message = "Purchase successfully saved!" }, JsonRequestBehavior.AllowGet);
}