Hello Team,
I use below function for saving data into my Sql Database from my controller and it works fine and as am trying to use same function for update query but is not working.
public ActionResult SaveItem(ItemViewModel itemModel) { var result = false; try { decimal costPrice = itemModel.CostPrice; decimal sellingPrice =itemModel.ItemPrice; decimal Profit = sellingPrice - costPrice; tblCategory objCategory = new tblCategory(); if (itemModel.CategoryId > 0) { objCategory = objRestaurantDBEntities.tblCategories .FirstOrDefault(x => x.CategoryId == itemModel.CategoryId); } else { objCategory.CategoryName = itemModel.CategoryName;
objRestaurantDBEntities.tblCategories.Add(objCategory); objRestaurantDBEntities.SaveChanges();
// Assign the generated CategoryId after save itemModel.CategoryId = objCategory.CategoryId; }
tblQuantity objQnty = new tblQuantity(); if (itemModel.QuantityId > 0) { objQnty = objRestaurantDBEntities.tblQuantities .FirstOrDefault(x => x.QuantityId == itemModel.QuantityId); } objQnty.Quantity = itemModel.Quantity; objQnty.QuantityId = itemModel.QuantityId;
if (itemModel.QuantityId <= 0) { objRestaurantDBEntities.tblQuantities.Add(objQnty); }
tblItem objItem = new tblItem(); if (itemModel.ItemId > 0) { objItem = objRestaurantDBEntities.tblItems .FirstOrDefault(x => x.ItemId == itemModel.ItemId); } objItem.PCode = itemModel.PCode; objItem.ItemName = itemModel.ItemName; objItem.CostPrice = itemModel.CostPrice; objItem.ItemPrice = itemModel.ItemPrice; objItem.Profit = Profit; objItem.CategoryId = itemModel.CategoryId; objItem.Active = itemModel.Active;
if (itemModel.ItemId <= 0) { objRestaurantDBEntities.tblItems.Add(objItem); }
objRestaurantDBEntities.SaveChanges(); result = true; } catch (Exception ex) { return Json(new { success = false, message = "An error occurred while saving the item." }); }
return Json(new { success = result, message = "Item saved successfully." }); }
function UpdateforProduct(ItemId) { var itemModel = new Object(); itemModel.PCode = $("#pCode").val(); itemModel.CategoryId = $("#categoryId").val(); itemModel.QuantityId = $("#qtyId").val(); itemModel.Quantity = $("#quantity").val(); itemModel.ItemId = $("#itemId").val(); itemModel.ItemName = $("#itemName").val(); itemModel.CostPrice = $("#txtCostPrice").val(); itemModel.ItemPrice = $("#itemPrice").val(); itemModel.Active = $("#status").val(); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'JSON', type: 'POST', url: '@Url.Action("SaveItem", "Home")',
data: JSON.stringify({ itemModel: itemModel }), success: function (response) { if (response.message) { //alert(response.message = "Success") toastr.success(response.message = "Product successfully updated!"); DataTable.ajax.reload();
$("#exampleModal").modal('hide'); } }, error: function (msg) { toastr.danger(msg.responseText); } });
}