2012-02-19 21 views
3

我有一個MVC視圖,將幾個模型發回控制器。我有要求添加允許用戶從同一表單添加X個「Infractions」的功能。我想要做的事情可以與將「Infractions」對象的IEnumerable回發給控制器進行比較。如果有一些方法來做到這一點,將是巨大的:我可以以同一形式將模型的多個實例傳遞給控制器​​嗎?

[HttpPost] 
public ActionResult Create(IEnumerable<Infractions> infractions) 

然後,我會遍歷IEnumerable和添加的違法行爲。

有什麼建議嗎?

回答

2

這絕對有可能。有關此問題,請參閱Phil Haack's post

訣竅是呈現正確格式的初始get屬性名稱,以便模型聯編程序將其識別爲列表/數組。

例如:

<input type='text' name='[0].Property1OnInfractions' /> 
<input type='text' name='[0].Property2OnInfractions' /> 

<input type='text' name='[1].Property1OnInfractions' /> 
<input type='text' name='[1].Property2OnInfractions' /> 


你的情況,你有你的IEnumerable轉換爲IList中得到以下工作:

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

和行動的簽名應該是這樣的

[HttpPost] 
public ActionResult Create(List<Infractions> infractions) 
+0

簽名是不是更好:''公開ActionResult創建(IList 違規)'? – 2012-02-19 10:35:16

+0

@jimtollan,原始代碼更具通用性,因爲'IEnumerable'仍然可以在HttpPost上工作,但有人編輯我的答案給List::( – 2012-02-20 05:24:21

相關問題