删除Item后如何返回索引页并关闭模态局部视图?
解决删除Item后返回索引页并关闭模态框的问题
先修复后端代码笔误
你的OnGetDelete方法里存在变量名错误,应该将Invoice改为Item,否则Partial视图无法获取正确的Item数据:
public PartialViewResult OnGetDelete(int id) { Item = _ItemApplication.GetDetails(id); // 修正变量名 return Partial("Delete", Item); }
方案1:前端AJAX处理(推荐,体验更流畅)
这种方式会先关闭模态框,再跳转索引页,用户体验更好。假设你使用Bootstrap模态框,在Delete局部视图中添加AJAX提交逻辑:
- 给表单设置ID,绑定提交事件:
<form id="deleteItemForm" method="post" asp-page-handler="Delete" asp-route-id="@Model.Id"> <!-- 模态框内容,比如删除确认提示 --> <div class="modal-body"> 确定要删除这条Item吗? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="submit" class="btn btn-danger">删除</button> </div> </form>
- 添加JavaScript处理提交和后续操作:
document.getElementById('deleteItemForm').addEventListener('submit', async function(e) { e.preventDefault(); // 阻止默认表单跳转 const form = this; // 发送删除请求 const response = await fetch(form.action, { method: form.method, body: new FormData(form) }); if (response.ok) { const result = await response.json(); if (result.status) { // 关闭模态框 const modalElement = document.getElementById('你的模态框ID'); // 替换为实际模态框ID const modal = bootstrap.Modal.getInstance(modalElement); modal.hide(); // 跳转到索引页 window.location.href = '/Index'; // 替换为你的索引页实际路径 } } });
方案2:后端直接跳转(简单但体验一般)
如果不需要保留模态框关闭的动画,可直接在OnPostDelete中返回索引页跳转:
public IActionResult OnPostDelete(int id) { _ItemApplication.Delete(id); return RedirectToPage("Index"); // 替换为你的索引页页面名称 }
这种方式会在删除完成后直接跳转,模态框会被页面刷新覆盖,没有关闭动画。
内容的提问来源于stack exchange,提问作者Mardibak
相关产品推荐
相关产品推荐

