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 PaulPosted Jan 22, 2025, 1:26 AM
update the JS code like this:
let's update your C# action method:
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.
Emmmanuel FIADUFEPosted Jan 22, 2025, 9:53 PM
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; }
}
Emmmanuel FIADUFEPosted Jan 22, 2025, 9:37 PM
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 FIADUFEPosted Jan 22, 2025, 12:38 PM
I'm wondering if this error could occur as a result of the date format which is not working properly
Emmmanuel FIADUFEPosted Jan 22, 2025, 10:11 AM
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 FIADUFEPosted Jan 22, 2025, 7:14 AM
Thank you Mr Paul for your swift response, I will update the code accordingly and revert
Tuhin PaulPosted Jan 22, 2025, 1:35 AM
Check below the flowchart. hope it might help.
Tuhin PaulPosted Jan 22, 2025, 1:23 AM
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.