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

2024-01-11

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

Model:

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; }
    }

View:

@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>

}


我会改变你的模型集合来使用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/ http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC 表单模型为复杂对象集合返回 null 的相关文章

随机推荐