首页 > 解决方案 > ASP.NET Core 2.2 剃刀视图中的操作按钮

问题描述

假设我们正在重新设计下面的视图:

在此处输入图像描述

当前代码是:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Url)
        </td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.BlogId">Edit</a> |
            <a asp-action="Details" asp-route-id="@item.BlogId">Details</a> |
            <a asp-action="Delete" asp-route-id="@item.BlogId">Delete</a>
        </td>
    </tr>
}

我们的目标是删除Delete每一行中链接的视图。相反,我们希望有一个删除按钮,在确认后删除行而不离开Index页面(重新加载很好)。

如何实现这样的按钮?是否有任何相关文件?

标签: razorasp.net-coreasp.net-core-mvc

解决方案


您可以使用 ajax 发出删除请求,以便用户可以在删除过程中停留。ajax 请求成功后,您可以从 UI 中删除表格行。

首先,为您的锚标记添加一个新属性,您可以使用该属性为您的 jQuery 选择器连接点击事件。

<a asp-action="Delete" ajaxy asp-route-id="@item.BlogId">Delete</a>

在这里,我添加了一个名为ajaxy

现在我们将click使用该属性监听锚标记上的事件ajaxy,停止正常行为(导航到 href 属性值 URL),而是进行 ajax 调用。要进行确认,您可以使用window.confirmAPI。

@section Scripts
{
    <script>

        $(function () {
            $("a[ajaxy]").click(function (e) {
                e.preventDefault();

                if (window.confirm("Are you sure ?")) {

                    var $this = $(this);
                    var url = $this.attr("href");
                    $.post(url).done(function (res) {
                        $this.closest("tr").fadeOut(300, function (a) {
                            $(this).remove();
                        });
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        alert("error in ajax call!" + errorThrown);
                    })
                }
            });
        });

    </script>
}

假设您的Delete操作接受Id参数。

[HttpPost]
public async Task<IActionResult> Delete(int id)
{
   // to do : return something     
}

推荐阅读