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

ASP.NET MVC:如何通过ModelState删除表格指定行(非jQuery实现)

实现每行删除按钮的解决方案

修改View代码

确保所有表单元素包裹在Html.BeginForm中,同时为每行的删除按钮设置带索引的value值,让控制器能识别要删除的目标行:

@using (Html.BeginForm("Test", "YourController", FormMethod.Post))
{
    @for (int i = 0; i < Model.ValueModel.Count; i++)
    {
        <div>
            <table>
                <tr>
                    <td>
                        @Html.DropDownListFor(m => m.ValueModel[i].id, new SelectList(Model.ReplaceModel, "id", "Name"))
                    </td>
                    <td>
                        @Html.EditorFor(m => m.ValueModel[i].value)
                    </td>
                    <td>
                        <button name="submit" value="RemLine-@i">Remove Line</button>
                    </td>
                </tr>
            </table>
        </div>
    }

    <button name="submit" value="AddLine">Add Line</button>
}

修改Controller代码

通过解析submit参数的值提取目标行索引,执行对应移除操作:

[HttpPost]
public ActionResult Test(TestModel model, string submit)
{
    if (submit == "AddLine")
    {
        model.ValueModel.Add(new ValueModel());
    }
    else if (submit.StartsWith("RemLine-"))
    {
        // 解析行索引并做边界校验,避免非法参数报错
        if (int.TryParse(submit.Split('-')[1], out int rowIndex) 
            && rowIndex >= 0 
            && rowIndex < model.ValueModel.Count)
        {
            model.ValueModel.RemoveAt(rowIndex);
        }
    }

    // 注意:如果ReplaceModel是从数据库等动态源获取的,需在此重新赋值
    // model.ReplaceModel = YourDataSource.GetReplaceItems();

    return View(model);
}

关键注意事项

  • 所有交互元素必须放在表单内部,否则无法触发Post请求完成行的增删。
  • 确保TestModel的ValueModel属性是List<ValueModel>类型,支持RemoveAt方法。
  • 对解析出的索引做边界检查,防止手动篡改提交参数导致索引越界异常。
  • 若下拉列表的数据源ReplaceModel是动态数据,每次Post后需重新加载,否则下拉选项会丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:05:48