Emmmanuel FIADUFE

Emmmanuel FIADUFE

  • 780
  • 1.1k
  • 55.6k

Controller said Object Undefined

Jul 14 2023 8:49 AM

Hello Team,

Am having some chanllegings here, I am trying to pass data from my controller to the database through my  modelView,

But keep getting this error, object undefined.

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.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.Status = productModel.Status;
        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 (3)