Emmmanuel FIADUFE

Emmmanuel FIADUFE

  • 798
  • 966
  • 43.3k

Object reference not set

Oct 24 2023 10:16 PM

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<tblCategory>();
                    }
                    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);

        }


Answers (2)