我有以下 View 模型
public class ResourceProjectedCapacitiesModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Location { get; set; }
public string Manager { get; set; }
public string Role { get; set; }
public string Project { get; set; }
public decimal Capacity { get; set; }
public System.DateTime Date { get; set; }
}
在我的 GET 操作中,我在 View 中显示所有这些。
[HttpPost]
public ActionResult Index(List ResourceProjectedCapacitiesModel> list)
{
foreach (ResourceProjectedCapacitiesModel item in list)
{
....
}
....
}
在 View 中有以下编辑器,但提交表单时绑定(bind)不起作用,列表为空
@Html.EditorFor(modelItem => item.Capacity)
@Html.HiddenFor(modelItem => item.ID)
@model List<CapacityPlanner.ViewModels.ResourceProjectedCapacitiesModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using(Html.BeginForm())
{
<table class="table">
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Location
</th>
<th>
Manager
</th>
<th>
Role
</th>
<th>
Project
</th>
<th>Apr</th>
<th>May</th>
<th>Jun</th>
<th>Jul</th>
<th>Aug</th>
<th>Sep</th>
<th>Oct</th>
<th>Nov</th>
<th>Dec</th>
<th>Jan</th>
<th>Feb</th>
<th>Mar</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Location)
</td>
<td>
@Html.DisplayFor(modelItem => item.Manager)
</td>
<td>
@Html.DisplayFor(modelItem => item.Role)
</td>
<td>
@Html.DisplayFor(modelItem => item.Project)
</td>
@for(var i = 1; i <= 12; i++)
{
<td>
@if(item.Date.Month == i)
{
@Html.EditorFor(modelItem => item.Capacity)
}
</td>
}
<td>
@Html.HiddenFor(modelItem => item.ID)
</td>
</tr>
}
</table>
<input type="submit" value="Save" class="btn btn-default" />
}
我已经插入了我的 View 的代码
最佳答案
您应该使用 for 而不是 foreach。
@for (int i = 0; i < Model.Items.Count; i++)
{
@Html.EditorFor(model => Model.Items[i].Amount)
@Html.HiddenFor(model => Model.Items[i].Amount)
}
那么所有填充的都会得到不同的id。
关于c# - 多重编辑上的 MVC 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23811872/