2016-04-23 56 views
2

請原諒我,如果這個問題是重複的,因爲我無法找到Stack Overflow其他任何地方的這個問題的答案。如何從ASP.NET中的表單訪問字段數組?

我在ASP.NET中有一個窗體有多個字段,並且可以通過jQuery添加更多字段。在我的形式中,我想要一些朋友。

這是友元類:

public class Friend { 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

這是我的形式,用戶可以通過點擊一個按鈕,增加了一排這兩個領域,因爲他們需要添加任意多的朋友。例如:

<table> 
    <tr> 
     <input type="text" name="friend[0].Name" /> 
     <input type="text" name="friend[0].Age" /> 
    </tr> 
    <tr> 
     <input type="text" name="friend[1].Name" /> 
     <input type="text" name="friend[1].Age" /> 
    </tr> 
    <tr> 
     <input type="text" name="friend[2].Name" /> 
     <input type="text" name="friend[2].Age" /> 
    </tr> 
    ... 
</table> 

如何在控制器中的函數中將這些列表作爲朋友列表訪問?

回答

3

我覺得你差不多了,

<form method="post" action="/Home/UpdateFriends"> 

    <input type="text" name="[0].Name" value="Curious George" /> 
    <input type="text" name="[0].Age" value="20" /> 

    <input type="text" name="[1].Name" value="Code Complete" /> 
    <input type="text" name="[1].Age" value="50" /> 



    <input type="submit" /> 
</form> 

控制器看起來應該像這樣

//Action method on HomeController 
public ActionResult UpdateFriends(ICollection<Friend> friends) { 
    //your code here 
} 

this article解釋了它更爲深入。

+0

謝謝你的幫助! – qazwsxedcrfvtgbyhnujmikolp

相關問題