You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SweetAlert2删除分类后Toastr未显示成功提示,报错toastr未定义

问题:Toastr.js未定义错误,无法显示删除成功提示

需求为点击删除按钮时,先通过SweetAlert2弹出确认框,确认删除分类后,用Toastr.js显示成功提示。但目前分类能成功删除,却报Uncaught ReferenceError: toastr is not defined错误,无法显示Toastr提示。


CategoryController代码

#region API CALLS

// https://localhost:7230/Admin/Category/getall => 获取所有Category属性的json数据用于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 = "无效ID" });
    }

    var categoryToBeDeleted = _unitOfWork.Category.Get(category => category.Id == id.Value);

    if (categoryToBeDeleted == null)
    {
        TempData["error"] = "分类不存在或已被删除。";
        return Json(new { success = false, message = "删除出错" });
    }

    _unitOfWork.Category.Remove(categoryToBeDeleted);
    _unitOfWork.Save();

    return Json(new { success = true, message = "分类删除成功" });
}

#endregion

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">分类数据</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> &nbsp;添加分类
            </a>

            <!-- 新建/编辑分类模态框 -->
            <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>编辑分类</span>
                                    }
                                    else
                                    {
                                        <span>添加新分类</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">
                                <!-- 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">分类名称</label>
                                    <input type="text" class="form-control" id="CategoryName" name="CategoryName"
                                           value="@TempData["CategoryName"]" required placeholder="分类名称" />
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-success">保存</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>序号</th>
                        <th>分类名称</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
            </table>
        </div>
    </div>
</div>

@section Scripts {
    <script src="~/js/category.js"></script>
}

category.js代码

$(function () {
    loadDataTable();
});

var dataTable;

function loadDataTable() {

    dataTable = $('#tableData').DataTable({
        "ajax": { url: '/admin/category/getall' },
        "columns": [
            {
                "data": null, // 序号列
                "render": function (data, type, row, meta) {
                    return meta.row + 1; // 显示行索引+1作为序号
                },
                "width": "10%"
            },
            { data: 'categoryName', "width": "30%" },
            { data: 'createdAt', "width": "25%" },
            {
                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> 编辑
                                    </a>
                                    <a onClick="Delete('/admin/category/delete/${data}')" 
                                       class="btn btn-danger ms-2" style="box-shadow:none">
                                       <i class="fas fa-trash"></i> 删除
                                    </a>
                                </div>
                            </div>
                            `
                },
                "width": "35%"
            }
        ],
        "columnDefs": [
            { "className": "dt-left", "targets": 0 } // 序号列左对齐
        ]
    });
}

function Delete(url) {
    Swal.fire({
        title: "确定要删除吗?",
        text: "删除后无法恢复!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "是的,删除!"
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'DELETE',
                success: function (data) {
                    /* 删除后重新加载数据 */
                    dataTable.ajax.reload();
                    // 错误:Uncaught ReferenceError: toastr is not defined                          
                    toastr.success(data.message);
                }
            });
        }
    });
}

错误信息

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)

解决方案

错误核心原因是页面未引入Toastr.js的依赖文件,浏览器无法识别toastr对象,解决步骤如下:

  1. 引入Toastr的CSS和JS文件
    在Index.cshtml的Scripts区块中,将Toastr的依赖放在category.js之前引入(确保加载顺序正确):
@section Scripts {
    <!-- 引入Toastr样式 -->
    <link href="~/lib/toastr/toastr.min.css" rel="stylesheet" />
    <!-- 引入Toastr脚本 -->
    <script src="~/lib/toastr/toastr.min.js"></script>
    <!-- 自定义脚本 -->
    <script src="~/js/category.js"></script>
}

注:路径需根据项目中Toastr文件的实际位置调整,若用CDN引入则替换为对应CDN链接。

  1. 可选:配置Toastr默认参数
    如需自定义提示框的位置、样式等,可在category.js开头添加配置:
// Toastr默认配置
toastr.options = {
    "closeButton": true,
    "progressBar": true,
    "positionClass": "toast-top-right",
    "timeOut": "5000",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
};
  1. 验证依赖加载顺序
    确保依赖加载顺序正确:
  • jQuery(页面已引入,因为使用了$.ajax)
  • Toastr JS
  • 自定义脚本category.js

修改完成后,删除分类成功时即可正常显示Toastr的成功提示。


内容的提问来源于stack exchange,提问作者Maruf Hasnat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 10:34:54