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

如何让多个提交按钮向控制器传递同一URL中的ID值?

解决两个删除按钮无法获取URL中ID的问题

问题根源

视图从带ID的Delete动作URL加载,但表单提交时未将该ID传递给Delete和DeleteBoth的Post动作,导致后者接收的ID为null。

可行解决方案

方案1:添加ID隐藏字段

在表单中新增绑定URL中ID的隐藏字段,让两个按钮提交时自动携带ID参数:

<form asp-action="">
    <!-- 新增隐藏字段传递ID -->
    <input type="hidden" value="@ViewContext.RouteData.Values["id"]" name="id" />
    <input type="hidden" asp-for="patient.emailAddress" />
    <input type="submit" value="Delete patient only" class="btn btn-danger" asp-action="Delete"/>
    <input type="submit" value="Delete patient and user" class="btn btn-danger" asp-action="DeleteBoth"/>
    <a asp-action="Index">Back to List</a>
</form>

方案2:给按钮指定路由参数

直接在每个提交按钮上通过asp-route-id显式传递URL中的ID:

<form asp-action="">
    <input type="hidden" asp-for="patient.emailAddress" />
    <input type="submit" value="Delete patient only" class="btn btn-danger" 
           asp-action="Delete" asp-route-id="@ViewContext.RouteData.Values["id"]"/>
    <input type="submit" value="Delete patient and user" class="btn btn-danger" 
           asp-action="DeleteBoth" asp-route-id="@ViewContext.RouteData.Values["id"]"/>
    <a asp-action="Index">Back to List</a>
</form>

方案3:给表单设置全局路由参数

为表单本身添加asp-route-id,让所有提交按钮默认携带ID参数:

<form asp-action="" asp-route-id="@ViewContext.RouteData.Values["id"]">
    <input type="hidden" asp-for="patient.emailAddress" />
    <input type="submit" value="Delete patient only" class="btn btn-danger" asp-action="Delete"/>
    <input type="submit" value="Delete patient and user" class="btn btn-danger" asp-action="DeleteBoth"/>
    <a asp-action="Index">Back to List</a>
</form>

控制器方法验证

当前的控制器Post方法定义无需修改,可正常接收ID参数:

[HttpPost]
public IActionResult Delete(string id)
{
    // 业务逻辑代码
}

[HttpPost]
public IActionResult DeleteBoth(string id)
{
    // 业务逻辑代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:20:34