2014-09-01 32 views
0
結合

我的模式是:如何實現模型的複雜類型

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") 

但我想要使用模型綁定功能。

回答

1

您需要使用for循環(你需要從IEnumerable集合改變IListname屬性索引正確

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

另外,您可以爲SupplierContact創建EditorTemplate和使用

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

+0

謝謝。我錯過了MVC呈現控件的方式。 – 2014-09-01 12:03:58

0

看看顯示和編輯器模板。比你可以創建一個叫做SupplierContact的視圖。如果他看到複雜類型,MVC會自動知道顯示的內容。

見這個例子:在你的看法文件夾DisplayTemplates: 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

因此,創建一個文件夾。 然後創建一個名爲SupplierContact的部分視圖。 將局部視圖的模型設置爲SupplierContact。 創建顯示標籤並再次運行應用程序。

要編輯,請創建EditorTemplates文件夾。

+0

這將是一個漫長的過程.. – 2014-09-01 12:40:26

+0

漫長的過程?這是在2分鐘內完成的。這是它應該在MVC中完成的方式。通過這種方式,當您顯示或編輯該類型的對象時,每個視圖都是相同的。 – 2014-09-01 13:39:55

+0

我更喜歡我接受的答案。不介意。 – 2014-09-01 15:51:23