通过表单从HTML Razor View传递一个列表

时间:2018-02-07 12:35:01

标签: c# html asp.net-mvc razor model-view-controller

这是My Tennant Class,其中包含联系人列表

public class Tennant
    {
        public Tennant()
        {
            ContactPerson = new List<HR.ContactPerson>();
        }
        public int Id { get; set; }
        public string CompanyName { get; set; }
        public string BrandName { get; set; }
        public string OfficeAddress { get; set; }

        public List<ContactPerson> ContactPerson { get; set; }

    }

这是联系人类

  public class ContactPerson
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public long CNIC { get; set; }
        public DateTime CNICExpiry { get; set; }
        public long MobileNumber { get; set; }
        public string Email { get; set; }
        public Address Address { get; set; }
    }

我无法理解如何为列表

创建视图(表单)
 <div class="form-group">
                @Html.LabelFor(x => x.CompanyName, new { })
                @Html.TextBoxFor(x => x.CompanyName, new { @class = "form-control", id = "CompanyName", placeholder = "Enter Company Name", type = "text" })
                <small id="companyName" class="form-text text-muted">Use M/S first.</small>
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.BrandName)
                @Html.TextBoxFor(x => x.BrandName, new { @class = "form-control", id = "BrandName", placeholder = "Enter Brand Name", type = "text" })
                <small id="brandName" class="form-text text-muted">Full Product / Brand Name</small>
            </div>
            <div class="form-group">
                @Html.LabelFor(x => x.OfficeAddress)
                @Html.TextBoxFor(x => x.OfficeAddress, new { @class = "form-control", id = "OfficeAddress", placeholder = "Enter Office Address", type = "text" })
                <small id="officeAddress" class="form-text text-muted">Full Office Address.</small>
            </div>

无法理解如何管理联系人列表

 @Html.TextBoxFor(x=>x.ContactPerson.)

我应该怎么做?

提前完成。

1 个答案:

答案 0 :(得分:1)

您需要使用for - 循环,然后默认的模型绑定器才能工作:

@for (int i = 0; i < Model.ContactPerson.Count; ++i)
{
    @Html.TextBoxFor(x => x.ContactPerson[i].FirstName)
}

注意:您需要在列表中添加“空”ContactPerson个实例,以获取新人的输入字段。