微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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" />

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐