Hello Team.
I have purchase table and purchaseItem table with thier respective modelView. and in my ajax post request I keep getting this error, Object reference not set to an instance of an object. kindly assist.
function SavePurchases()
{
debugger;
var purchaseModel = new Object();
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 PurchaseItemsViewModel = {};
debugger;
//PurchaseItemModel.ItemID = parseFloat($(this).find("td:eq(0)").text());
PurchaseItemsViewModel.ItemName = String($(this).find("td:eq(0)").text());
PurchaseItemsViewModel.Batch = parseFloat($(this).find("td:eq(5)").text());
PurchaseItemsViewModel.Qty = parseFloat($(this).find("td:eq(2)").text());
PurchaseItemsViewModel.CostPrice = parseFloat($(this).find("td:eq(3)").text());
PurchaseItemsViewModel.SellingPrice = parseFloat($(this).find("td:eq(4)").text());
PurchaseItemsViewModel.Expiry = Date($(this).find("td:eq(6)").html());
//var dateText = $(this).find("td:eq(6)").text().trim();
//var parts = dateText.split('/');
//var formattedDate = new Date(parts[2], parts[1] - 1, parts[0]); // Month is 0-based
//PurchaseItemModel.Expiry = formattedDate;
// Assuming Moment.js is included in the project
//var dateText = $(this).find("td:eq(6)").text().trim();
//var formattedDate = moment(dateText, "DD/MM/YYYY").format("YYYY-MM-DD");
//PurchaseItemModel.Expiry = formattedDate;
ListOfPurchaseItemsViewModel.push(PurchaseItemsViewModel);
});
ListOfPurchaseItemsViewModel.purchaseModel = ListOfPurchaseItemsViewModel;
//post data to server
$.ajax({
async: true,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "JSON",
url: "/PurchaseEntry/SavePurchase",
data: JSON.stringify(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');
}
});
}
public ActionResult SavePurchase(PurchaseItem purchaseModel)
{
var result = false;
try
{
tblPurchase objPurchase = new tblPurchase();
if (purchaseModel.tblPurchase.PurchaseID > 0)
{
objPurchase = objASPNETPHARMACYDBEntities.tblPurchases.Where(x => x.PurchaseID == purchaseModel.PurchaseID).FirstOrDefault
}else
{
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;
if (purchaseModel.tblPurchase.PurchaseID <= 0)
objASPNETPHARMACYDBEntities.tblPurchases.Add(objPurchase);
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;
}
if (purchaseModel.PurchaseItemID <= 0)
{
objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(updatePurchase);
}
objASPNETPHARMACYDBEntities.SaveChanges();
result = true;
}
catch (Exception ex)
{
throw ex;
//return Json(new { result = true, message = "Purchase fails to save!" }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = true, message = "Purchase successfully saved!" }, JsonRequestBehavior.AllowGet);
}

Tuhin PaulRank #7 · 71.9K reputationPosted Jan 21, 2025, 8:26 PM EST
update the JS code like this:
function SavePurchases() { var purchaseModel = { tblPurchase: { PurchaseID: $.trim($('#PurchaseID').val() + '--' + $('#SelectSupplier').val()), Date: $('#InvocingDate').val().trim(), SupplierID: $('#SelectSupplier').val(), Amount: parseFloat($('#Amount').val()), Discount: parseFloat($('#Discount').val()), Tax: parseFloat($('#Tax').val()), GrandTotal: parseFloat($('#GrandTotal').val()), IsPaid: $('#Payment').is(":checked") ? 1 : 0, Description: $('#Description').val() }, PurchaseItems: [] }; $("#orderItems").find("tr:gt(0)").each(function () { var purchaseItem = { ItemName: $(this).find("td:eq(0)").text(), Batch: parseFloat($(this).find("td:eq(5)").text()), Qty: parseFloat($(this).find("td:eq(2)").text()), CostPrice: parseFloat($(this).find("td:eq(3)").text()), SellingPrice: parseFloat($(this).find("td:eq(4)").text()), Expiry: $(this).find("td:eq(6)").text() }; purchaseModel.PurchaseItems.push(purchaseItem); }); $.ajax({ async: true, contentType: "application/json; charset=utf-8", type: "POST", dataType: "JSON", url: "/PurchaseEntry/SavePurchase", data: JSON.stringify(purchaseModel), success: function (d) { if (d.result == true) { alert(d.message); location.reload(true); } else { alert('Failed: ' + d.message); } }, error: function (xhr, status, error) { alert('Error: ' + xhr.responseText); } }); }let's update your C# action method:
public class PurchaseViewModel { public tblPurchase tblPurchase { get; set; } public List PurchaseItems { get; set; } } public class PurchaseItemViewModel { public string ItemName { get; set; } public float Batch { get; set; } public float Qty { get; set; } public float CostPrice { get; set; } public float SellingPrice { get; set; } public string Expiry { get; set; } } [HttpPost] public ActionResult SavePurchase(PurchaseViewModel purchaseModel) { if (purchaseModel == null || purchaseModel.tblPurchase == null) { return Json(new { result = false, message = "Invalid data received." }, JsonRequestBehavior.AllowGet); } try { tblPurchase objPurchase = new tblPurchase(); // Map properties from purchaseModel.tblPurchase to objPurchase 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.tblPurchases.Add(objPurchase); objASPNETPHARMACYDBEntities.SaveChanges(); foreach (var item in purchaseModel.PurchaseItems) { tblPurchaseItem purchaseItem = new tblPurchaseItem { PurchaseID = objPurchase.PurchaseID, ItemID = GetItemIdByName(item.ItemName), // You need to implement this method Batch = item.Batch, Qty = item.Qty, CostPrice = item.CostPrice, SellingPrice = item.SellingPrice, Expiry = DateTime.Parse(item.Expiry) }; objASPNETPHARMACYDBEntities.tblPurchaseItems.Add(purchaseItem); } objASPNETPHARMACYDBEntities.SaveChanges(); return Json(new { result = true, message = "Purchase successfully saved!" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { result = false, message = "Error: " + ex.Message }, JsonRequestBehavior.AllowGet); } } // Implement this method to get ItemID by ItemName private int GetItemIdByName(string itemName) { // Query your database to get the ItemID based on the ItemName // Return the ItemID throw new NotImplementedException(); }Modification done are as follows:
Created a `PurchaseViewModel` that matches the structure of the data sent from the client.
Updated the JavaScript code to properly structure the data before sending it to the server.
Modified the C# action method to handle the new data structure and perform proper null checks.
Simplified the purchase saving process by always creating a new purchase instead of updating an existing one.
You need to implement the `GetItemIdByName` method to retrieve the correct `ItemID` based on the `ItemName` you're receiving from the client.
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 21, 2025, 8:23 PM EST
The `PurchaseItem` model you're receiving doesn't match the structure of the data you're sending from the client.
In your JavaScript code, you're creating a `purchaseModel` object, but you're not including the `ListOfPurchaseItemsViewModel` in it.
The server is expecting a `PurchaseItem` object, but it's receiving just the `purchaseModel` without the list of items.
Tuhin PaulRank #7 · 71.9K reputationPosted Jan 21, 2025, 8:35 PM EST
Check below the flowchart. hope it might help.
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2025, 2:14 AM EST
Thank you Mr Paul for your swift response, I will update the code accordingly and revert
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2025, 5:11 AM EST
Hello Mr Paul.
when I implement this method and I tried to save data, the data got save only in the purchase tabel whiles purcahseItem item table remain empty and this the error message that came.
// Query your database to get the ItemID based on the ItemName // Return the ItemID
this is my method for calling ItemId based on the ItemName.
private int GetItemIdByName(string itemName)
{
try
{
// Query your database to get the ItemID based on the ItemName
// Return the ItemID
var itemId = (from item in objASPNETPHARMACYDBEntities.tblItems
where item.ItemName == itemName
select item.ItemID).FirstOrDefault();
return itemId;
}
catch (Exception)
{
// Log the exception
// ...
// Re-throw the exception or return a default value
throw new NotImplementedException();
}
}
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2025, 7:38 AM EST
I'm wondering if this error could occur as a result of the date format which is not working properly
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2025, 4:37 PM EST
Hello Mr Paul.
when I implement this method and I tried to save the data, the data got save only in the purchase table whiles purcahseItem table remain empty.
I change the model content and the JS structure as you said but this error keeps coming, reference not set to an instance of a string. Parameter name:s,
What could be the cause of this error.
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2025, 4:53 PM EST
This is my model
public class PurchaseItem
{
[Key]
public int PurchaseItemID { get; set; }
public int PurchaseID { get; set; }
public int ItemID { get; set; }
public string Batch { get; set; }
public string ItemName { get; set; }
[Range(0, 1000000, ErrorMessage = "Not an acceptable Quantity!")]
public int Qty { get; set; }
[Range(0.00, 99999999.99)]
public decimal CostPrice { get; set; }
public decimal SellingPrice { get; set; }
[DisplayFormat(DataFormatString = "{yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public string Expiry { get; set; }
public virtual Item Item { get; set; }
public virtual PurchaseViewModel tblPurchase { get; set; }
}