2013-12-12 122 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