如何在Razor页面中为多行数据设置单个提交按钮?
解决方案
核心问题分析
之前调整form位置后出现ID绑定错误,是因为表单内存在多个name="id"的隐藏输入框,ASP.NET Core模型绑定会默认取第一个匹配字段的值,导致无论选中哪一行,传递的都是第一行的ID。
具体修改步骤
1. 重构视图结构
把整个表格包裹在单个<form>中,用全局隐藏字段存储选中的联系人ID,同时给每个checkbox添加自定义属性关联对应ID:
@model IEnumerable<ContactModel> <form method="post" asp-action="EditContacts"> <!-- 全局隐藏字段:存储选中的联系人ID --> <input type="hidden" id="selectedContactId" name="id" value="" /> <table class="table table-stripped table-bordered text-center"> <thead> <tr> <th>no</th> <th>address</th> <th>confirm address</th> </tr> </thead> <tbody> @{ int id = 0; foreach (var contact in Model) { id++; <tr> <td>@id</td> <td>@contact.Address</td> <td> <!-- 用data属性存储当前联系人ID,去掉原行内的form --> <input type="checkbox" class="h4 form-check-input single-checkbox" name="isValid" value="true" data-contact-id="@contact.Id" /> </td> </tr> } } </tbody> </table> <!-- 单个提交按钮,默认隐藏 --> <button type="submit" id="submitButton" class="btn btn-primary mt-3" style="display:none;">确认选中地址</button> </form>
2. 更新JS逻辑
修改脚本,实现选中checkbox时自动更新全局隐藏字段的值,并控制提交按钮显示:
@section Scripts { <script> $(document).ready(function() { $('.single-checkbox').change(function() { // 取消其他checkbox的选中状态 $('.single-checkbox').not(this).prop('checked', false); // 获取当前选中项对应的联系人ID const selectedId = $(this).data('contact-id'); // 更新全局隐藏字段的值 $('#selectedContactId').val(selectedId); // 根据选中状态切换提交按钮显示/隐藏 $('#submitButton').toggle($('.single-checkbox:checked').length > 0); }); }); </script> }
3. 后端Action无需修改
原有的EditContacts Action可以保持不变,因为表单提交时会正确传递选中的id和isValid参数。
效果说明
- 页面仅显示一个提交按钮,位于表格下方。
- 选中任意一行的checkbox时,会自动将对应联系人ID存入隐藏字段,提交表单时后端能正确接收选中行的ID。
- 依然保留单选逻辑,同一时间只能选中一个checkbox。
内容的提问来源于stack exchange,提问作者Aboliii
相关产品推荐
相关产品推荐

