从 jQuery 核心项目的 jQuery 数据表和数据库中删除数据时出现问题

Problem with deleting data from jQuery Datatable and database in ASP.NET Core project

我正在使用 jQuery 数据 table 来可视化每个用户完成的付款信息。我在 table 中创建了“编辑”和“删除”按钮。但是,删除按钮不起作用 - 我想我没有正确触发 PaymentsController 的 Action 方法。我的 paymentsTable.js 有以下脚本:

$(document).ready(function () {
    $("#paymentsTable").DataTable({
        "processing": true,
        "responsive": true,
        "serverSide": true,
        "filter": true,
        "language": {
            "lengthMenu": "Показване на _MENU_ плащания на страница",
            "zeroRecords": "Няма открити съвпадения",
            "info": "Открити са _PAGE_ от _PAGES_ плащания",
            "infoEmpty": "Няма плащания",
            "infoFiltered": "(претърсено от _MAX_ плащания общо)",
        },
        "ajax": {
            "url": "/Users/GetUserPayments",
            "beforeSend": function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            {
                "targets": [0],
                "visible": false,
                "searchable": false,
                "className": "dt-body-center",
            },
            {
                "targets": 1,
                "render": function (data, type, row) {
                    return (data)
                        ? moment(data, "YYYY-MM-DD").format("DD/MM/YYYY")
                        : null;
                }
            },
        ],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "dateOfPayment", "name": "DateOfPayment", "autoWidth": true },
            { "data": "description", "name": "Description", "autoWidth": true },
            { "data": "amount", "name": "Amount", "autoWidth": true },
            {
                "render": function (data, type, full, meta) {
                    return "<a class='btn btn-secondary border border-white' onclick=GoToEditView('" + full.id + "'); >Edit</a> <a class='btn btn-secondary border border-white' onclick=DeleteData('" + full.id + "'); >Delete</a>";
                },
            },
        ]
    });
});

function GoToEditView(id) {
    window.location.href = 'https://localhost:44319/Payments/Edit/' + id;
}

function DeleteData(id) {
    if (confirm("Наистина ли желаете да изтриете данните за това разплащане?")) {
        Delete(id);
    } else {
        return false;
    }
}

function Delete(id) {
    $.ajax({
        type: 'POST',
        url: "/Payments/Delete",
        data: { id: id },
        success: function (r) {
            window.location.reload();
        }
    });
}
我的控制器有以下代码:

[Authorize(Roles = GlobalConstants.AdministratorRoleName)]
public class PaymentsController : Controller
{
    private readonly IPaymentsService paymentsService;

    public PaymentsController(
        IPaymentsService paymentsService)
    {
        this.paymentsService = paymentsService;
    }

    public IActionResult Create(string id)
    {
        return this.View();
    }

    [HttpPost]
    public async Task<IActionResult> Create(string id, PaymentInputModel input)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(input);
        }

        try
        {
            await this.paymentsService.CreateAsync(input, id);
        }
        catch (Exception e)
        {
            this.ModelState.AddModelError(string.Empty, e.Message);
            return this.View(input);
        }

        return this.Redirect("/Users/ById/" + id);
    }

    [HttpPost]
    public async Task<IActionResult> Delete(string id)
    {
        await this.paymentsService.DeleteAsync(id);

        var userId = this.HttpContext.Session.GetString("userId");

        return this.RedirectToAction("/Users/ById/" + userId);
    }

    public IActionResult Edit(string id)
    {
        var inputModel = this.paymentsService.GetById<PaymentInputModel>(id);

        return this.View(inputModel);
    }

    [HttpPost]
    public async Task<IActionResult> Edit(string id, PaymentInputModel input)
    {
        if (!this.ModelState.IsValid)
        {
            return this.View(input);
        }

        await this.paymentsService.UpdateAsync(id, input);

        id = input.UserId;

        return this.RedirectToAction(nameof(UsersController.ById), "Users", new { id });
    }
}

这是我的 ById.cshtml 文件(用户的个人资料视图),它由 UsersController 触发。这是我希望 paymentsTable 可视化的地方。

@model ChessBurgas64.Web.ViewModels.Users.UserProfileViewModel
@using ChessBurgas64.Common
@using ChessBurgas64.Data.Models.Enums

@{
    this.ViewData["Title"] = String.Concat(Model.FirstName, " ", Model.MiddleName, " ", Model.LastName);
}

<link href="~/lib/datatables.net-bs5/dataTables.bootstrap5.min.css" rel="stylesheet" />

<h1 class="text-white text-center display-5">@GlobalConstants.Profile</h1>

<div class="container-fluid background-dragon-red border border-3 border-white pt-2 mb-5">
    <h3 class="display-6 text-white text-center">@this.ViewData["Title"]</h3>
</div>


<div class="row container-fluid">
    <div class="col-md-6">
        <h4 class="display-6 text-white text-center">@GlobalConstants.PersonalData</h4>
        <hr class="border border-5 border-white text-white" />

        <div class="bg-white border border-danger border-5 pt-2 text-left px-3 text-left">
            <p>@GlobalConstants.Gender: <i class="fa-solid fa-mars-and-venus"></i> @Model.Gender</p>
            <hr class="text-dark" />
            <p>@GlobalConstants.BirthDate: <i class="fa-solid fa-cake-candles"></i> @Model.BirthDate.ToShortDateString()</p>
            <hr class="text-dark" />

            @if (Model.Member != null)
            {
                <p>@GlobalConstants.Address: <i class="fa-solid fa-location-dot"></i> @Model.Member.Address</p>
                <hr class="text-dark" />
                <p>@GlobalConstants.School: <i class="fa-solid fa-school"></i> @Model.Member.School</p>
                <hr class="text-dark" />
            }

            <p>@GlobalConstants.ClubStatus: <i class="fa-solid fa-user"></i> @Model.ClubStatus</p>
            <hr class="text-dark" />
        </div>
    </div>

    <div class="col-md-6">
        <h4 class="display-6 text-white text-center">@GlobalConstants.ClubData</h4>
        <hr class="border border-5 border-white text-white" />

        <div class="bg-white border border-danger border-5 pt-2 text-left px-3">
            @if (Model.Member != null)
            {
                <p>@GlobalConstants.ClubRating: <i class="fa-solid fa-star"></i> @Model.Member.ClubRating</p>
                <hr class="text-dark" />
                <p>@GlobalConstants.DateOfJoiningTheClub: <i class="fa-solid fa-flag-checkered"></i> @Model.Member.DateOfJoiningTheClub.ToShortDateString()</p>
                <hr class="text-dark" />

                @if (Model.Member.Group != null)
                {
                    <p>@GlobalConstants.Group: <i class="fa-solid fa-user-group"></i> @Model.Member.Group.Name</p>
                    <hr class="text-dark" />
                    <p>@GlobalConstants.DateOfJoiningCurrentGroup: <i class="fas fa-calendar-alt"></i> @Model.Member.DateOfJoiningCurrentGroup.ToShortDateString()</p>
                    <hr class="text-dark" />
                }
                else
                {
                    <p>@GlobalConstants.Group: <i class="fa-solid fa-user-group"></i> @GlobalConstants.None</p>
                    <hr class="text-dark" />
                }

                <p>@GlobalConstants.LastAttendance: <i class="fas fa-calendar-alt"></i> @Model.Member.DateOfLastAttendance.ToShortDateString()</p>
                <hr class="text-dark" />
            }
            else
            {
                @GlobalConstants.MemberStillNotAddedToTheSystem
            }
        </div>
    </div>

    <div class="text-center my-2">
        @if (Model.ClubStatus == ClubStatus.Треньор.ToString())
        {
            <a class="btn btn-primary" asp-action="EditTrainerInfo" asp-route-id="@Model.Id">@GlobalConstants.Edit</a>
        }
        else
        {
            <a class="btn btn-primary" asp-action="EditMemberInfo" asp-route-id="@Model.Id">@GlobalConstants.Edit</a>
        }
    </div>

    <div class="container-fluid text-center">
        <h4 class="display-6 text-white text-center mt-3">@GlobalConstants.Payments</h4>
        <hr class="border border-5 border-white text-white" />
        <div class="text-white py-2 container-fluid" style="width:100%; margin:0 auto;">
            <table id="paymentsTable" class="bg-white table-bordered table-responsive text-dark compact border border-5 border-danger text-center" width="100%" cellspacing="0">
                <thead class="dt-head-center">
                    <tr>
                        <th class="dt-head-center">Id</th>
                        <th class="dt-head-center">@GlobalConstants.DateOfPayment</th>
                        <th class="dt-head-center">@GlobalConstants.PaidFor</th>
                        <th class="dt-head-center">@GlobalConstants.PaidAmount</th>
                        <th class="dt-head-center">@GlobalConstants.Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
        <a class="btn btn-primary" asp-area="" asp-controller="Payments" asp-action="Create" asp-route-id="@Model.Id">@GlobalConstants.AddPayment</a>
    </div>
</div>

@Html.AntiForgeryToken()

@section Scripts
{
    <script src="~/lib/datatables.net/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables.net-bs5/dataTables.bootstrap5.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
    <script src=" //cdn.datatables.net/plug-ins/1.10.11/sorting/datetime-moment.js"></script>
    <script src="~/js/paymentsTable.js"></script>
}

在调试时,我注意到在单击“删除”按钮后,我的 PaymentsController 中的“删除”操作方法根本没有被触发,并且状态代码为 400 时出现错误。我不确定具体如何删除调用此方法,因为我没有“DeleteView”。我对此很陌生,所以我可能遗漏了一些重要的东西。我尝试了不同的解决方案,其中 none 有效。请帮忙!

添加令牌,尝试使用下面的代码来更改您的删除 ajax:

function Delete(id) {
    $.ajax({
        type: 'POST',
        url: "/Payments/Delete",
        "beforeSend": function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
        data: { id: id },
        success: function (r) {
            window.location.reload();
        }
    });
}