如何实现复杂类型的模型绑定

时间:2014-09-01 11:21:00

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

我的模特是:

public class ContactInfo
        {

            public IEnumerable<SupplierContact> PriceRequest { get; set; }
            public IEnumerable<SupplierContact> OrderConfirmation { get; set; }
            public IEnumerable<SupplierContact> Account { get; set; }
        }




 public class SupplierContact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public string Email { get; set; }
        public string MobilePhone { get; set; }

    }

我的控制器操作是

public ActionResult EditContactInfo(ContactInfo contactInfo)
{
// not getting any values here..
}

视图渲染如下:

 @foreach (SupplierContact PriceRequest in Model.PriceRequest)
                {
                <tr class="">
                    <td style="text-align: left;" class="csstd-left">@Html.TextBoxFor(m => PriceRequest.Email)</td>
                    <td class="csstd">@Html.TextBoxFor(m => PriceRequest.MobilePhone)</td>
                    <td class="csstd">@PriceRequest.Title</td>
                    <td class="csstd">@PriceRequest.FirstName</td>
                    <td class="csstd">@PriceRequest.LastName</td>                  

                </tr>
                }

我在视图中引用@model ContactInfo

但是我可以使用

来实现它
Request.Form.Get("PriceRequest.Email")

但我想使用模型绑定功能。

2 个答案:

答案 0 :(得分:1)

您需要使用for循环(并且您需要将集合从IEnumerable更改为IList,并将name属性正确编入索引

@for (int i = 0; i < Model.PriceRequest.Count; i++) {
  @Html.TextBoxFor(m => Model.PriceRequest[0].Email)
  @Html.TextBoxFor(m => Model.PriceRequest[i].MobilePhone)
}

或者,您可以为EditorTemplate创建SupplierContact并使用

@Html.EditorFor(m => m.PriceRequest)

这将生成类似

的html
<input name="PriceRequest[0].Email" ...
<input name="PriceRequest[0].MobilePhone" ...
<input name="PriceRequest[1].Email" ...
<input name="PriceRequest[2].MobilePhone" ...

答案 1 :(得分:0)

查看显示和编辑器模板。您可以创建名为SupplierContact的视图。如果他看到复杂的类型,MVC会自动知道要显示的内容。

查看此示例: http://www.asp.net/mvc/tutorials/javascript/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc-part-2

因此,在views文件夹中创建一个文件夹:DisplayTemplates。 然后创建一个名为SupplierContact的局部视图。 将部分视图的模型设置为SupplierContact。 创建用于再次显示和运行应用程序的标签。

要进行编辑,请创建一个EditorTemplates文件夹。

相关问题