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 JoshiRank #377 · 6.7K reputationPosted Oct 25, 2023, 1:45 AM EDT
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:
public JsonResult SaveProduct(ProductViewModel productModel) { ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities(); var result = false; try { tblCategory category = new tblCategory(); if(productModel.tblCategory != null){ 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) { product = db.tblProducts.Where(a => a.ProductId == productModel.ProductId).FirstOrDefault(); } product.ProductName = productModel.ProductName; if(productModel.tblCategory != null) 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); }Thanks
Vishal Joshi
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Oct 25, 2023, 7:08 AM EDT
Great, thank Mr Vishal, it is working perfectly fine as per your explanation and correction