.NET Core MVC中通过模型绑定提交视图表格数据至Action的方法
.NET Core MVC 表格数据到Action的模型绑定实现方法
要实现表格数据通过模型绑定提交到Action,核心是让表单元素的name属性符合.NET Core列表绑定规则——格式为[视图模型列表属性名][索引].[子模型属性名](比如tableData[0].item1),下面分步骤实现:
1. 模型与视图模型(沿用你的定义,仅修正命名规范)
public class MyModel { public string Item1 { get; set; } public string Item2 { get; set; } } public class MyViewModel { public List<MyModel> TableData { get; set; } }
2. 渲染可提交的表格(含初始数据)
把展示型表格改成带输入框的可提交结构,用for循环代替foreach生成带索引的name属性,这是模型绑定识别列表数据的关键:
<form method="post" asp-action="SubmitTableData"> <table> <tr> <th>Item1</th> <th>Item2</th> <th>操作</th> </tr> @for (int i = 0; i < Model.TableData.Count; i++) { <tr> <td><input type="text" name="TableData[@i].Item1" value="@Model.TableData[i].Item1" /></td> <td><input type="text" name="TableData[@i].Item2" value="@Model.TableData[i].Item2" /></td> <td><button type="button" class="delete-row">删除</button></td> </tr> } </table> <button type="button" id="add-row">添加行</button> <button type="submit">提交</button> </form>
3. 动态添加行的JS实现
如果需要用户手动添加行,编写JS生成带有正确name属性的表格行,删除行后建议更新索引保证连续性:
// 添加行逻辑 document.getElementById('add-row').addEventListener('click', function() { const table = document.querySelector('table'); const rowCount = table.querySelectorAll('tr').length - 1; // 减去表头行 const newRow = document.createElement('tr'); newRow.innerHTML = ` <td><input type="text" name="TableData[${rowCount}].Item1" /></td> <td><input type="text" name="TableData[${rowCount}].Item2" /></td> <td><button type="button" class="delete-row">删除</button></td> `; table.appendChild(newRow); bindDeleteEvent(newRow); }); // 删除行逻辑 function bindDeleteEvent(row) { row.querySelector('.delete-row').addEventListener('click', function() { row.remove(); updateRowIndices(); }); } // 更新所有行的索引(保证绑定正常) function updateRowIndices() { const rows = document.querySelectorAll('table tr:not(:first-child)'); rows.forEach((row, index) => { const inputs = row.querySelectorAll('input'); inputs[0].name = `TableData[${index}].Item1`; inputs[1].name = `TableData[${index}].Item2`; }); } // 初始化绑定删除事件 document.querySelectorAll('.delete-row').forEach(btn => { bindDeleteEvent(btn.parentElement.parentElement); });
4. Action接收数据
在Controller中直接接收MyViewModel参数,模型绑定会自动将表单数据填充到TableData列表:
[HttpPost] public IActionResult SubmitTableData(MyViewModel viewModel) { // viewModel.TableData即为提交的表格数据,可直接用于后续业务处理 return RedirectToAction("Index"); }
关键注意事项
- 表单元素的
name属性必须严格匹配[列表属性名][索引].[子属性名]格式,大小写不敏感但建议与模型属性名一致 - .NET Core 3.1及以上版本支持无索引格式
TableData[].Item1,但避免与其他同名非列表字段冲突 - 删除行后更新索引可避免因索引断层导致部分数据无法绑定
内容的提问来源于stack exchange,提问作者Vahid.M
相关产品推荐
相关产品推荐

