2013-12-12 35 views
4

我有一个包含4行(移动,工作,单元格,电子邮件)和5列以上的表格。当我POST时,我不收回任何数据。我可以重构代码以使其工作吗?复杂对象集合返回null的MVC表单模型

型号

public class ContactInfoViewModel { 

    public string HomePhone { get; set; } 
    public ICollection<bool> HomePhoneChecks { get; set; } 
    public string MobilePhone { get; set; } 
    public ICollection<bool> MobilePhoneChecks { get; set; } 
    public string WorkPhone { get; set; } 
    public ICollection<bool> WorkPhoneChecks { get; set; } 
    public string Email { get; set; } 
    public ICollection<bool> EmailChecks { get; set; } 

    public string Email2 { get; set; } 

    public IEnumerable<RowData> Rows { get; set; } 

    public IEnumerable<RowData> GetAllRows() { 
     return new List<RowData> { 
       new RowData { Name = "HomePhone", Label = "Home Phone", Heading = HomePhone, Columns = HomePhoneChecks}, 
       new RowData { Name = "MobilePhone", Label = "Mobile Phone", Heading = MobilePhone, Columns = MobilePhoneChecks}, 
       new RowData { Name = "WorkPhone", Label = "Work Phone", Heading = WorkPhone, Columns = WorkPhoneChecks}, 
       new RowData { Name = "Email", Label = "Email", Heading = Email, Columns = EmailChecks}, 
      }; 
    } 

    public class RowData { 
     public string Name { get; set; } 
     public string Label { get; set; } 
     public string Heading { get; set; } 
     public ICollection<bool> Columns { get; set; } 
    } 

查看

@foreach (var row in Model.ContactInfo.GetAllRows()) { 
<tr> 
    <td class="boxRows noMargin"> 
     <div> 
      <div class="boxLabel">@row.Label</div> 
      <div class="boxValue">@Html.TextBoxFor(m => row.Heading)</div> 
     </div> 
    </td> 
    @foreach (var item in row.Columns) { 
     <td>@Html.CheckBoxFor(m => item)</td> 
    } 
</tr> 

}

+1

没有'你的模型ContactInfo'财产。 – VahidN

回答

4

我会改变你的模型集合,以使用List特性是能够模型绑定。

举个例子:

public List<RowData> AllRows { get; set; } 

然后你的循环改变这种将由模型绑定拾取。

@for (int i = 0; i < Model.AllRows.Count; i++) 
    { 
     ..... 
     @Html.EditorFor(model => Model.AllRows[i].Heading) 
     ..... 
    } 

然后他们将被回发到服务器。

欲了解更多信息就可以在这里看到:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

+0

通常我会使用编辑器模板,但是因为我通过JavaScript动态添加元素,这不是一个选项。即使对于动态对象,您推荐的这种解决方案也可以工谢谢 – BrianLegg

+0

@BrianLegg没问题。 – hutchonoid