我是implementing an example基于 EF Core
和 RazorPages
来执行简单的CRUD .
现在特别是代表"List"视图的第2页(Index.cshtml) . 每行包含一个 button
元素以供删除 .
来自 Products.cshtml
的片段
<form method="POST">
@foreach(var product in Model.Products) {
<button type="submit" asp-page-handler="delete" asp-route-id="@product.Id">delete</button>
<!-- the one below doesn't work with my custom Javascript -->
<!-- <button data-confirm type="submit" asp-page-handler="delete" asp-route-id="@product.Id">delete</button> -->
}
</form>
来自 Products.cshtml.cs
的片段
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var product = await _db.Products.FindAsync(id);
if (product != null)
{
//_db.Products.Remove(product);
//await _db.SaveChangesAsync();
}
return RedirectToPage();
}
Up to this point it works. I can click the delete button and I see a successful redirect back to the page.
现在我想使用Javscript添加自定义确认功能 . 我可以在这个上下文中使用jQuery,所以我基本上拦截所有 data-confirm
属性按钮并阻止默认操作,所以我只能在用户确认时提交 .
$('button[data-confirm]').each(function() {
var currentElement = this;
var currentForm = currentElement.form;
$(currentElement).click(function (e) {
e.preventDefault();
var confirmValue = $(currentElement).attr('data-confirm');
var confirmText = confirmValue ? confirmValue : 'Are you sure?';
bootbox.confirm(confirmText, function (result) {
if (result) {
currentForm.submit();
}
});
});
});
使用我的新功能 RazorPage
机制不会调用 OnPostDeleteAsync
...我应该如何提交表单"manually"以符合RazorPages提交的要求?
1 回答
我基本上必须考虑
button
元素上生成的formaction
属性 . 将此值设置为表单操作使其工作 .