我正在尝试创建一个非常简单的表单来回发模型集合中的一些值
当我单击提交,并查看返回的集合时,它不包含任何对象.我还认为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>
解决方法
将您的模型更改为@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" />
因此,您可以看到您应该通过索引访问列表项以正确呈现输入的名称属性.另外,不要忘记通过隐藏输入包含其他项目属性,否则它将在后期操作中释放.