2014-05-22 47 views
2

结合我有以下视图模型MVC模型的多个编辑

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) 
    { 
     .... 
    } 
    .... 
} 

在有以下编辑器,但是当表单提交的约束力不工作,列表为空

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

我已经插入我的观点的代码视图

+0

您可以添加您的视图的整个代码?含。 '@ model' defenition和'foreach'循环。这将有助于诊断问题。 –

+0

您如何期望将单个模型发送到视图,但返回列表?这甚至没有意义。 –

+0

我是唯一一个没有意识到这一点的人吗? –

回答

3

你应该使用而不是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。

+0

仍然无效 – den

+0

为什么'Model.Items [i] .Amount'?为什么不只是'Model [i] .Amount'?模型本身就是名单还是我错过了什么? –

+0

@Elad Lachm这是一个快速的例子。尝试添加'@ Html.HiddenFor(model => Model [i] .Item)'foreach填充。更改'@foreach(模型中的var项){'to for。 – Svmurvj