MVC形模型返回null复杂的对象集合 [英] MVC Form Model returning null for complex object collection

查看:133
本文介绍了MVC形模型返回null复杂的对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4行(移动,工作,细胞,电子邮件),和5+列的表。当我发布,我不回来任何数据。我可以重构code,使其工作?

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?

型号

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>

}

推荐答案

我会改变你的模型集合,以使用能够模型绑定的列表属性。

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

作为一个例子:

   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/

这篇关于MVC形模型返回null复杂的对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆