DataTable delete Button
{
"data": "ProductId", "width": "50px", "render": function (data) { return "Delete"; }
},
JAVASCRIPT
function DeleteProduct(ProductId) {
swal({
title: 'Do you want to delete Data?',
showCancelButton: true,
showConfirmButton: true,
confirmButtonText: 'Yes Delete',
cancelButtonText: 'No pls cancel',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
type: 'warning',
buttonsStyling: false
}).then(function (isConfirm) {
// Called if you click Yes.
if (isConfirm) {
// Make Ajax call.
$.ajax({
type: "POST",
url: "/Home/DeleteProduct" + ProductId,
data: { ProductId: ProductId },
contentType: 'application/json; charset=ut-8',
dataType: 'json',
})
swal('Confirmed', '1 Product deleted successfully', 'success');
}
},
function (no) {
// Called if you click No.
if (no == 'cancel') {
swal('Cancelled', '', 'error');
}
});
}
HomeController
public ActionResult DeleteProduct(int ProductId)
{
try
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
var product = db.tblProducts.Find(ProductId);
db.tblProducts.Remove(product);
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 10, 2023, 11:03 AM EST
Hello,
Try below code.
function DeleteProduct(ProductId) { swal({ title: 'Do you want to delete Data?', showCancelButton: true, showConfirmButton: true, confirmButtonText: 'Yes Delete', cancelButtonText: 'No pls cancel', confirmButtonClass: 'btn btn-success', cancelButtonClass: 'btn btn-danger', type: 'warning', buttonsStyling: false }).then(function (isConfirm) { // Called if you click Yes. if (isConfirm) { // Make Ajax call. $.ajax({ type: "POST", url: "/Home/DeleteProduct/" + ProductId, data: { ProductId: ProductId }, contentType: 'application/json; charset=ut-8', dataType: 'json', success: function (data) { if (data) { swal('Confirmed', '1 Product deleted successfully', 'success'); } else { swal('Error', 'Failed to delete product', 'error'); } }, error: function () { swal('Error', 'Failed to delete product', 'error'); } }); } }, function (no) { // Called if you click No. if (no == 'cancel') { swal('Cancelled', '', 'error'); } }); }Thanks
Naimish Makwana
Vishal JoshiRank #377 · 6.7K reputationPosted Feb 11, 2023, 3:09 AM EST
Hello,
your code looks good. i think it's placed inside some other function so it's not working. try to place at outside of another function so It will work fine.
Also, change the ajax call with the below code to show the SWAL analysis after ajax call is complete.
$.ajax({ type: "POST", url: "/Home/DeleteProduct/" + ProductId, data: { ProductId: ProductId }, contentType: 'application/json; charset=ut-8', dataType: 'json', success: function (response) { if (response) { swal('Confirmed', '1 Product deleted successfully', 'success'); } else { swal('Error', 'Failed to delete product', 'error'); } });Thanks