2011-11-03 19 views
3

菲爾哈克有介紹如何設置的東西,所以默認模型綁定將綁定到一個集合上回發了一篇文章:如何獲得上回發的視圖模型子集合在MVC3?

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

我有是我不只是想問題將集合發回Controller控制器操作,但將ViewModel與集合一起發送。

我有一個類,基本上是這樣的:

public class MyViewModel 
{ 
public int IncidentNumber { get; set; } 
public string StoreId { get; set; } 
public string RepId { get; set; } 
public string OrderStatus { get; set; } 
public CustomerViewModel Customer { get; set; 
//... other properties and SelectLists for binding 

public IEnumerable<OrderItemViewModel> OrderItemViewModels { get; set; } 

其實我可以得到CustomerViewModel數據傳回回發,但OrderItemViewModels的列表是空的。我怎樣才能讓他們回來?菲爾的文章沒有幫助那裏。

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    ... some input fields 

    @Html.EditorFor(x => x.OrderItemViewModels) 

    <input type="submit" value="OK" /> 
} 

,然後相應的編輯器模板,將裏面:

回答

5

我這裏MVC binding to model with list property ignores other properties這是通過使用視圖中的下列代碼

<div class="editor-field"> 
@for (int i = 0; i < Model.MyCollection.Count(); i++) 
{ 
    @Html.HiddenFor(m => m.MyCollection[i].Id) 
    @Html.HiddenFor(m => m.MyCollection[i].ParentId) 
    @Html.HiddenFor(m => m.MyCollection[i].Name) 
    @Html.TextBoxFor(m => m.MyCollection[i].Value) 
} 
</div> 
+1

我給你豎起大拇指的這一點,因爲它本質上是正確的答案。我瞭解到,它是HTML Input元素的Name屬性。它必須是在一定的格式(如其他線程顯示),以便模型綁定弄明白。以及您的具體答案是正確的(我不得不處理下拉框,不得不手動覆蓋Name屬性來得到這個工作) –

+0

謝謝!花了太多時間找到這個答案,我希望更多的人+1。 – jhilden

1

使用編輯模板解決了類似的問題自動輸出呈現爲OrderItemViewModels集合中的每個元素(~/Views/Shared/EditorTemplates/OrderItemViewModels.cshtml):

@model OrderItemViewModels 
<div> 
    @Html.LabelFor(x => x.Prop1) 
    @Html.EditorForFor(x => x.Prop1) 
</div> 
<div> 
    @Html.LabelFor(x => x.Prop2) 
    @Html.EditorForFor(x => x.Prop2) 
</div> 
... 
+0

達林,這不太有效,因爲單個項目上的命名不適合數據綁定到參數。 –

相關問題