MVC模型绑定多个编辑

时间:2014-05-22 15:59:39

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我有以下视图模型

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操作中,我在视图中显示所有这些。

[HttpPost]
public ActionResult Index(List ResourceProjectedCapacitiesModel> list)
{
    foreach (ResourceProjectedCapacitiesModel item in list)
    {
        ....
    }
    ....
}

在视图中有以下编辑器但是当提交表单时绑定不起作用,list为null

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

我已插入了我的观点代码

1 个答案:

答案 0 :(得分:3)

你应该使用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)
}

然后所有填充的内容都会有不同的身份。