asp.net-core – 模型集合上的ModelBinding

我正在尝试创建一个非常简单的表单来回发模型集合中的一些值

当我单击提交,并查看返回的集合时,它不包含任何对象.我还认为asp-for不会生成我期望的集合索引.

我有一个简单的模型

public class CustomModel
{
    public int Id { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

这是我的观点

@model ICollection<CustomModel>
<form asp-action="Index" asp-controller="Home" method="POST">
<table>
    @foreach (var m in Model)
    {
        <tr>
            <td><label asp-for="@Model">@m.Question</label><input asp-for="@m.Answer"/></td>
        </tr>
    }
</table>
<input type="submit" value="save" />

呈现页面时的外观示例:

<tr>
            <td><label>Your name?</label><input type="text" id="m_Answer" name="m.Answer" value="" /></td>
        </tr>
        <tr>
            <td><label>Your Age?</label><input type="text" id="m_Answer" name="m.Answer" value="" /></td>
        </tr>

这是我假设它会有一个索引,但它看起来像是将每一行视为一个神经模型而不是一组模型.

在这做错了什么?这是一个错误,还是设计?

Github测试项目
https://github.com/lasrol/TestModelBindingList

解决方法

将您的模型更改为@model List< CustomModel>
而不是使用下一个方法

<form asp-action="Index" asp-controller="Home" method="POST">
<table>
    @for (int i = 0; i < Model.Count; i++)
    {            
        <tr>
            <td>
                <input type="hidden" asp-for="@Model[i].Id" />
                <input type="hidden" asp-for="@Model[i].Question" />            
                <label asp-for="@Model[i].Question">@(Model[i].Question)</label>
                <input asp-for="@Model[i].Answer" />
            </td>
        </tr>            
    }
</table>
<input type="submit" value="save" />

因此,您可以看到您应该通过索引访问列表项以正确呈现输入的名称属性.另外,不要忘记通过隐藏输入包含其他项目属性,否则它将在后期操作中释放.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....