首页 > 解决方案 > 如何在尝试使用 Razor Pages 删除 ASP.NET Core 中的记录时显示确认消息

问题描述

我正在使用 Razor Pages,并且在用户单击删除按钮时似乎很难显示确认消息。

在我的 Index.cshtml 上,我有:

<a asp-page-handler="Delete" asp-route-id="@item.Id" id="deleteBtn" class="btn bg-danger mr-1"><i class="fas fa-trash-alt text-white"></i></a>

这些是作为 foreach 循环的一部分生成的。

我的删除方法:

public async Task<IActionResult> OnGetDelete(Guid id)
{
    if (id == null)
    {
        return NotFound();
    }

    var record = await _context.LoadTable.FindAsync(id);

    if (record != null)
    {
        _context.LoadTable.Remove(record);
        await _context.SaveChangesAsync();
    }

    return RedirectToPage("./Index");
}

我正在使用 Bootstrap,所以理想情况下希望使用它的模式来显示消息。显示消息不是问题,而是我需要停止触发该方法,直到用户确认这是他们想要做的事情,并且使用 Razor Pages,我似乎正在挣扎。

我的想法是在模式中有删除按钮,而删除按钮显示模式,但我不确定如何传递@item.Id。

或者使用JavaScript来拦截按钮点击?

标签: javascriptc#twitter-bootstrapasp.net-corerazor

解决方案


我认为出于安全原因,最好将按钮放入form执行操作DELETE

使用这种方法,您可以尝试:

<form asp-page-handler="Delete" method="OnGetDelete" asp-route-id="@item.Id" 
       onclick="return confirm('Are you sure you want to delete this?')">
  <button type="submit" class="btn btn-default"><i class="fas fa-trash-alt text-white"></i></button>
</form>

推荐阅读