I want to show a successful delete message by using toastr.js when any user will click on the delete button, first it will show alert, so I use sweetalert2.js, but after confirming delete in sweetalert2.js, it is only deleting the category but it is not showing the success message in toastr.js rather than showing the error: Uncaught ReferenceError: toastr is not defined
In CategoryController:
#region API CALLS
// https://localhost:7230/Admin/Category/getall => to get all the propoerties of Category in json for using in datatable
[HttpGet]
public IActionResult GetAll()
{
List<Category> objCategoryList = _unitOfWork.Category.GetAll().ToList();
return Json(new { data = objCategoryList });
}
[HttpDelete]
public IActionResult Delete(Guid? id)
{
if (!id.HasValue)
{
return Json(new { success = false, message = "Invalid ID" });
}
var categoryToBeDeleted = _unitOfWork.Category.Get(category => category.Id == id.Value);
if (categoryToBeDeleted == null)
{
TempData["error"] = "Category not found or already deleted.";
return Json(new { success = false, message = "Error while deleting" });
}
_unitOfWork.Category.Remove(categoryToBeDeleted);
_unitOfWork.Save();
return Json(new { success = true, message = "Category deleted successfully" });
}
#endregion
In Index.cshtml:
@model IEnumerable<Category>
<div class="container mt-4">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<h5 class="mb-0">Categories Data</h5>
<a asp-controller="Category" asp-action="Upsert" class="btn btn-primary" style="box-shadow: none" data-bs-toggle="modal" data-bs-target="#categoryModal">
<i class="fas fa-plus-circle"></i> Add Category
</a>
<!-- Modal for Create/Update Category -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form asp-controller="Category" asp-action="Upsert" method="post">
<div class="modal-header">
<h5 class="modal-title" id="categoryModalLabel">
@if (TempData["CategoryId"] != null)
{
<span>Edit Category</span>
}
else
{
<span>Add New Category</span>
}
</h5>
<button type="button" style="box-shadow: none" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<!-- Hidden Field for Id -->
<input type="hidden" id="Id" name="Id" value="@(TempData["CategoryId"] ?? Guid.Empty.ToString())" />
<div class="mb-3">
<label for="CategoryName" class="form-label fw-bold ms-1">Category Name</label>
<input type="text" class="form-control" id="CategoryName" name="CategoryName"
value="@TempData["CategoryName"]" required placeholder="Category Name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Dismiss</button>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="card-body">
<table id="tableData" class="table table-bordered table-striped" style="width: 100%">
<thead class="thead-light">
<tr>
<th>S/N</th>
<th>Category Name</th>
<th>Created At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
@section Scripts {
<script src="~/js/category.js"></script>
}
In category.js:
$(function () {
loadDataTable();
});
var dataTable;
function loadDataTable() {
dataTable = $('#tableData').DataTable({
"ajax": { url: '/admin/category/getall' },
"columns": [
{
"data": null, // Serial number column
"render": function (data, type, row, meta) {
return meta.row + 1; // Display row index + 1 for serial number
},
"width": "10%"
},
{ data: 'categoryName', "width": "30%" },
{ data: 'createdAt', "width": "25%" },
//{ data: 'id', "width": "15%" },
{
data: 'id',
"render": function (data) {
return `<div class="d-flex justify-content-center">
<div class="w-75 btn-group" role="group">
<a href="/admin/category/upsert?id=${data}"
class="btn btn-warning text-white me-2" style="box-shadow:none" data-bs-toggle="modal" data-bs-target="#categoryModal">
<i class="fas fa-edit"></i> Edit
</a>
<a onClick="Delete('/admin/category/delete/${data}')"
class="btn btn-danger ms-2" style="box-shadow:none">
<i class="fas fa-trash"></i> Delete
</a>
</div>
</div>
`
},
"width": "35%"
}
],
"columnDefs": [
{ "className": "dt-left", "targets": 0 } // Apply left alignment to the serial number column (first column)
]
});
}
function Delete(url) {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url,
type: 'DELETE',
success: function (data) {
/*to reload the page after delete*/
dataTable.ajax.reload();
//Error: Uncaught ReferenceError: toastr is not defined
toastr.success(data.message);
}
});
}
});
}
Error:
Uncaught ReferenceError: toastr is not defined
at Object.success (category.js:65:21)
at c (jquery.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery.min.js:2:29072)
at l (jquery.min.js:2:79901)
at XMLHttpRequest.<anonymous> (jquery.min.js:2:82355)
You could try this below code. looks like there might be some issue in your original code that you are missing the reference of the js file.
Index.cshtml:
@{
ViewData["Title"] = "Category List";
}
<div class="container">
<h2>Category List</h2>
<table id="categoryTable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Created At</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div>
@section Scripts {
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
loadDataTable();
});
function loadDataTable() {
$('#categoryTable').DataTable({
"ajax": {
"url": "/Category/GetAll",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "id" },
{ "data": "categoryName" },
{ "data": "createdAt" },
{
"data": "id",
"render": function (data) {
return `<a onclick="Delete('/Category/Delete/${data}')" class="btn btn-danger">Delete</a>`;
}
}
]
});
}
function Delete(url) {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!"
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: url,
type: "DELETE",
success: function (data) {
if (data.success) {
$('#categoryTable').DataTable().ajax.reload();
toastr.success(data.message);
} else {
toastr.error(data.message);
}
}
});
}
});
}
</script>
}
CategoryController.cs:
using CategoryApp.DataAccess.Repository;
using CategoryApp.Models;
using Microsoft.AspNetCore.Mvc;
namespace CategoryApp.Controllers
{
public class CategoryController : Controller
{
private readonly IRepository<Category> _categoryRepository;
public CategoryController(IRepository<Category> categoryRepository)
{
_categoryRepository = categoryRepository;
}
[HttpGet]
public IActionResult GetAll()
{
var categories = _categoryRepository.GetAll();
return Json(new { data = categories });
}
[HttpDelete]
public IActionResult Delete(Guid? id)
{
if (!id.HasValue)
return Json(new { success = false, message = "Invalid ID" });
var category = _categoryRepository.Get(c => c.Id == id.Value);
if (category == null)
return Json(new { success = false, message = "Category not found" });
_categoryRepository.Remove(category);
return Json(new { success = true, message = "Category deleted successfully" });
}
}
}