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.
C#
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();
}
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;
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);
}
Vishal JoshiRank #377 · 6.7K reputationPosted Jul 14, 2023, 5:00 AM EDT
Hello,
Please check the API call from javascript sending model data in the correct format. it should be the same as model productModel.
Also, need to change in API code as below.
category = db.tblCategories.Where(x => x.CategoryId == productModel.CategoryId).FirstOrDefault(); //Replace with below category = db.tblCategories.Where(x => x.CategoryId == productModel.tblCategory.CategoryId).FirstOrDefault();Thanks
Vishal Joshi
Amit MohantyRank #112 · 20K reputationPosted Jul 14, 2023, 7:20 AM EDT
public JsonResult SaveProduct(ProductViewModel productModel) { ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities(); var result = false; try { tblCategory category = new tblCategory(); if (productModel.tblCategory != null && 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; product.Status = productModel.Status; product.CategoryId = category.CategoryId; // Use category.CategoryId instead of 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); }Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jul 14, 2023, 3:33 PM EDT
Thank you team,
Am so much greatful