MVC表单模型为复杂对象集合返回null

时间:2013-12-12 21:48:26

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

我有一个包含4行(移动,工作,单元格,电子邮件)和5列以上的表格。当我发布POST时,我没有收到任何数据。我可以重构代码以使其工作吗?

模型

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 个答案:

答案 0 :(得分: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/