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

如何将HTML动态表格内容绑定到ASP.NET Razor Pages模型的List集合

实现思路

Razor Pages 对集合类型的模型绑定有固定的命名规则:只要表单元素的name属性满足集合名[索引].属性名的格式,提交后后台就能自动把值映射到对应的List集合里。你要实现动态表格绑定ItensDescarte,按照下面的步骤修改即可:


第一步:后台PageModel配置

首先在你的.cshtml.cs后台页面类里,给要绑定的模型加[BindProperty]特性:

public class 你的页面类名 : PageModel
{
    // 给提交的模型加绑定特性
    [BindProperty]
    public SolicitacaoDescarteColeta Solicitacao { get; set; }

    // 初始化的时候给集合实例化,避免空引用
    public void OnGet()
    {
        Solicitacao ??= new SolicitacaoDescarteColeta();
        Solicitacao.ItensDescarte ??= new List<ItemDescarte>();
    }

    // 提交的处理方法
    public IActionResult OnPost()
    {
        // 此处Solicitacao.ItensDescarte就能自动拿到你表格里所有的条目
        if(ModelState.IsValid)
        {
            // 你的业务逻辑,比如存数据库
            return RedirectToPage("Success");
        }
        return Page();
    }
}

第二步:前端cshtml修改

你需要给点击添加条目的按钮加JS逻辑,每次新增行的时候按照绑定规则生成表单元素:
首先给你的加号按钮加个id方便绑定事件:

<i id="btnAddItem" class="bi bi-plus-square" style="cursor:pointer;"></i>

然后在页面底部加JS代码:

<script>
// 初始化索引,从0开始
let itemIndex = 0;

document.getElementById('btnAddItem').addEventListener('click', function(){
    const tipo = document.getElementById('tipo_item').value;
    const descricao = document.getElementById('item_descricao').value;
    
    // 先做非空校验
    if(!tipo || !descricao) {
        alert('请先选择物料类型和填写描述');
        return;
    }

    // 生成新的表格行,里面放隐藏的input用于提交,显示的是文本内容
    const newRow = `
    <tr>
        <td>${itemIndex + 1}</td>
        <td>
            ${tipo}
            <input type="hidden" name="Solicitacao.ItensDescarte[${itemIndex}].TipoDoItem" value="${tipo}" />
        </td>
        <td>
            ${descricao}
            <input type="hidden" name="Solicitacao.ItensDescarte[${itemIndex}].DescricaoDoItem" value="${descricao}" />
        </td>
    </tr>
    `;

    // 把行加到表格里
    document.getElementById('tabela_itens_body').insertAdjacentHTML('beforeend', newRow);

    // 索引自增,清空输入框
    itemIndex++;
    document.getElementById('tipo_item').value = '';
    document.getElementById('item_descricao').value = '';
});
</script>

第三步:表单提交

确保你的所有内容都放在<form method="post"></form>标签里,提交的时候所有隐藏的input都会被提交到后台,自动绑定到Solicitacao.ItensDescarte集合里。


注意事项

  • 如果你需要支持删除行的功能,删除之后要重新给所有隐藏input的索引重新排序,保证索引是连续的从0开始的数字,不然中间断号的条目会绑定不上。
  • 主键字段比如ItemDescarteID、SolicitacaoDescarteColetaID如果是新增数据的话不需要传,数据库会自动生成,编辑的时候再对应加上隐藏input传值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:02