MVC Form Model returning null for complex object c

2019-05-07 00:07发布

问题:

I have a table with 4 rows (mobile, work, cell, email), and 5+ columns. When I POST I don't get back any data. Can I refactor the code to make it work?

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>

}

回答1:

I would change your model collections to use List properties that are capable of model binding.

As an example:

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

Then change your loop to this which will be picked up by the model binder.

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

They will then be posted back to the server.

For more info on it see here:

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