Hello Team,
In my product dataTable I have status with column which represent Active and Inactive and when I want to update the column this error popup saying object reference not set, kindly help.
public JsonResult SaveProduct(ProductViewModel productModel)
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
var result = false;
try
{
tblCategory category = new tblCategory();
if (productModel.tblCategory.CategoryId > 0)
{
category = db.tblCategories.Where(x => x.CategoryId == productModel.tblCategory.CategoryId).FirstOrDefault
}
else
{
category.CategoryName = productModel.tblCategory.CategoryName;
if (productModel.tblCategory.CategoryId <= 0)
db.tblCategories.Add(category);
db.SaveChanges();
category.CategoryId = productModel.tblCategory.CategoryId;
}
tblProduct product = new tblProduct();
if (productModel.ProductId > 0)
{
product = db.tblProducts.Where(a => a.ProductId == productModel.ProductId).FirstOrDefault();
}
product.ProductName = productModel.ProductName;
product.CategoryId = productModel.tblCategory.CategoryId;
if (productModel.ProductId <= 0)
{
db.tblProducts.Add(product);
}
db.SaveChanges();
result = true;
}
catch (Exception ex)
{
throw ex;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
Vishal JoshiPosted Oct 25, 2023, 5:45 AM
Hello Emmanuel,
As per the error Need to check object is null or not. as per the code it looks like need to check productModel.tblCategory is null. if it's null no need to execute that code or skip that part of code from execution.
Please check the below code:
Thanks
Vishal Joshi
Emmmanuel FIADUFEPosted Oct 25, 2023, 11:08 AM
Great, thank Mr Vishal, it is working perfectly fine as per your explanation and correction