You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将forEach循环项ID传入asp-route-id?点击删除时ID返回0

问题原因

asp-route-id是ASP.NET Core的服务器端标签助手,页面渲染阶段就会被解析成最终的URL(比如/Index?handler=Delete&id=0)。你用JS修改asp-route-id属性时,页面已经完成渲染,这个属性不会再被服务器重新解析,所以实际请求的URL始终是初始的id=0。


解决方案

根据你的使用场景,提供三种可行方案:

方案1:单条数据直接绑定删除链接(最简洁)

如果是每行单独删除,无需复选框,直接在循环中为<a>标签绑定当前项的ID:

<table>
    @foreach(var item in Model.Items)
    {
        <tr>
            <td>@item.Name</td>
            <td>
                <a asp-page-handler="Delete" asp-route-id="@item.Id" class="btn btn-danger">删除</a>
            </td>
        </tr>
    }
</table>

页面渲染后,每个删除链接的href会自动生成对应ID的合法URL,无需JS干预。

方案2:JS动态修改<a>标签的href(单选中项删除)

如果必须通过复选框选中后删除,直接修改<a>的href属性(而非asp-route-id):

视图代码

<table>
    @foreach(var item in Model.Items)
    {
        <tr>
            <td><input type="checkbox" class="delete-checkbox" value="@item.Id"></td>
            <td>@item.Name</td>
        </tr>
    }
</table>

<a id="deleteBtn" asp-page-handler="Delete" asp-route-id="0" class="btn btn-danger">删除选中项</a>

JS代码

document.getElementById('deleteBtn').addEventListener('click', function(e) {
    const checkedBoxes = document.querySelectorAll('.delete-checkbox:checked');
    if (checkedBoxes.length === 0) {
        e.preventDefault();
        alert('请选择要删除的项');
        return;
    }
    // 取第一个选中项的ID
    const selectedId = checkedBoxes[0].value;
    // 替换URL中的id参数
    this.href = this.href.replace(/id=0/, `id=${selectedId}`);
});

方案3:表单提交实现批量删除(多选中项场景)

如果需要删除多个选中项,建议用表单提交传递ID数组,避免URL长度限制:

视图代码

<form method="post" asp-page-handler="Delete">
    @Html.AntiForgeryToken()
    <table>
        @foreach(var item in Model.Items)
        {
            <tr>
                <td><input type="checkbox" name="ids" value="@item.Id"></td>
                <td>@item.Name</td>
            </tr>
        }
    </table>
    <button type="submit" class="btn btn-danger">删除选中项</button>
</form>

后台模型代码

public IActionResult OnPostDelete(long[] ids)
{
    foreach(var id in ids)
    {
        // 执行你的删除逻辑
        _yourDataRepository.Delete(id);
    }
    _yourDataRepository.SaveChanges();
    return RedirectToPage();
}

注意事项

  • 生产环境中,删除操作建议用POST请求(配合防伪造令牌),避免浏览器误触或缓存问题;
  • 如果用GET请求处理删除,需要注意URL长度限制,批量删除场景优先用POST。

内容的提问来源于stack exchange,提问作者zahra rfe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:15:31