我有一个看法,我在一个循环中呈现了部分视图.列表中有一个列表,部分视图与每个项目绑定.输入值后,我没有得到控制器列表的值.
这是我的看法
- <table id="resourceRequirement" class="table" width="100%" border="0">
- <thead>
- <tr style="background-color:#dfdfdf;">
- <td><div align="center">PRIORITY</div></td>
- <td><div align="center">SYSTEM RESOURCE / COMPONENT</div></td>
- <td><div align="center">RECOVERY TIME OBJECTIVE</div></td>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model.ResourceRequirement)
- {
- @Html.Partial("~/Views/Shared/_ResourceRequirement.cshtml",item)
- }
- </tbody>
- </table>
这是我的部分看法:
- @model DisasterManagementSystem.Models.BusinessImpactAnalysis.ResourceRequirement
- <tr>
- <td>
- @Html.TextBoxFor(m => m.priority)<br />
- <div style="color:red;">
- @Html.ValidationMessageFor(model => model.priority)
- </div>
- </td>
- <td>
- @Html.TextBoxFor(m => m.systemresource)<br />
- <div style="color:red;">
- @Html.ValidationMessageFor(model => model.systemresource)
- </div>
- </td>
- <td>
- @Html.TextBoxFor(m => m.receveryTime)<br />
- <div style="color:red;">
- @Html.ValidationMessageFor(model => model.receveryTime)
- </div>
- </td>
- </tr>
这是我的清单:
- public List<ResourceRequirement> ResourceRequirement { get; set; }
班级在这里:
请告知我什么时候试图从列表中获取列表,我将该列表作为null.
解决方法
您使用foreach循环,部分生成不带索引器的重复名称属性(因此无法绑定到集合)和重复的id属性(无效的html).
而不是部分视图,请使用EditorTemplate.将您当前的部分视图重命名为ResourceRequirement.cshtml(即匹配类的名称),并将其放在/ Views / Shared / EditorTemplates文件夹(或/ Views / yourController / EditorTemplates文件夹中)
然后在主视图中,删除foreach循环并替换它
- <tbody>
- @Html.EditorFor(m => m.ResourceRequirement)
- </tbody>
EditorFor()方法接受IEnumerable< T>并为您的集合中的每个项目生成正确的html.如果您检查html,您将在窗体控件中看到正确的名称属性
- <input type="text" name="ResourceRequirement[0].priority" .... />
- <input type="text" name="ResourceRequirement[1].priority" .... />
- <input type="text" name="ResourceRequirement[2].priority" .... />