2011-12-07 94 views
2

嗨我想提交父母和子女,我可以提交父母罰款,但不是孩子,有沒有辦法做到這一點?提交父母和子女在剃刀

這是我的代碼。

@model IECWeb.Models.CurrencyDay 

using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 
<fieldset> 
    <legend>CurrencyDay</legend> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.CurrencyDate) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.CurrencyDate) 
     @Html.ValidationMessageFor(model => model.CurrencyDate) 
    </div> 

    <p /> 

    <table> 
     <tr> 
      <th>Currency</th> 
      <th>Rate</th> 
     </tr> 
     @foreach (var item in Model.Currency) { 
      <tr> 
       <td> 
        <div class="editor-field"> 
         @Html.EditorFor(model => item.Name) 
         @Html.ValidationMessageFor(model => item.Name) 
        </div> 
       </td> 
       <td> 
        <div class="editor-field"> 
         @Html.EditorFor(model => item.Rate) 
         @Html.ValidationMessageFor(model => item.Rate) 
        </div> 
       </td> 
      </tr> 
     } 
    </table> 

    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 

當我提交我得到CurrencyDay對象,但不是貨幣

感謝 sushiBite名單。

回答

5

我會使用編輯模板,而不是寫循環,建議您在訪問量:

<table> 
    <tr> 
     <th>Currency</th> 
     <th>Rate</th> 
    </tr> 
    @Html.EditorFor(x => x.Currency) 
</table> 

,然後在相應的編輯模板,這將是爲貨幣集合的每個元素提供(~/Views/Shared/EditorTemplates/CurrencyViewModel.cshtml):

@model CurrencyViewModel 
<tr> 
    <td> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 
    </td> 
    <td> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Rate) 
      @Html.ValidationMessageFor(model => model.Rate) 
     </div> 
    </td> 
</tr> 

請注意,編輯器模板的名稱和位置很重要。按照慣例,位置應該是~/Views/SomeController/EditorTemplates(如果模板在控制器的動作之間重用)或者更多全局~/Views/Shared/EditorTemplates。編輯器模板的名稱應該是您正在迭代的集合中每個元素的類型的名稱。

+0

謝謝,這工作得更好,我不需要將ICollection轉換爲列表,看起來更清潔:D我看到這個後需要重寫一些代碼:D再次感謝 – sushiBite

2

請閱讀Phil Haacks關於模型綁定到列表的文章。

Model Binding To A List

希望這有助於

+0

感謝這個作品,但達林的回答更多的是我正在尋找的方向。 – sushiBite