# C# MVC Controller 收Post進來的多筆資料(使用List)
實作上常常需要用一次收多筆資料給Controller,因為input可能是動態產生的
這邊附上可執行範例,底下逐一說明 https://dotnetfiddle.net/5ryBVA

---
## input區域
```html=
<input type="text" name"p[0].id" />
<input type="text" name"p[0].name" />
<input type="text" name"p[1].id" />
<input type="text" name"p[1].name" />
....
<input type="text" name"p[9].id" />
<input type="text" name"p[9].name" />
```
---
## 注意:陣列一定要從0開始,且不得跳號
前面的p[0]陣列一定要從0開始,且不得跳號
例如寫成p[0] p[1] p[3] ),會收不到東西
Controller在接收的時候,可以用List的型態一次全部收起來
```C#=
[httppost]
public ActionResult Edit(List<Member> p){
return View();
}
//這邊是為了教學方便才這樣寫,實際上建議放在viewmodel裡,反正view一定會用到
public class member {
int id {get;set;}
string name {get;set;}
}
```
---
## select-multiple 範例 (使用array收資料)
### view
```html=
<form action="Index" method="post">
<select multiple="" name="SelectOption">
<option value="value1">A</option>
<option value="value2">B</option>
<option value="value3">C</option>
</select>
<input type="submit" value="Save"/>
<form>
<!--Razor-->
@Html.ListBox("SelectOption", SelectOption_items, new { @class = "form-control select-multiple" })
```
### Model
```C#=
public Guid[] SelectOption { get; set; }
```
### Controller
```C#=
[HttpPost]
public ActionResult Index(Guid[] postback)
{
return View();
}
```
Model的名稱必須跟select的name屬性相同,post回來才接得上
---
## 參考文件
* MVC-利用集合接 View傳回的資料
https://dotblogs.com.tw/lastsecret/2010/05/28/15468
* ASP.NET MVC 表單提交List到Controller
http://www.cnblogs.com/talentzemin/p/5330726.html
* 使用陣列取值
Data binding in MVC 5 and Select2 Multiple Values with Razor engine
https://stackoverflow.com/questions/23417594/data-binding-in-mvc-5-and-select2-multiple-values-with-razor-engine
Razor mutliselect dropdown- set values as selected in the multiselect dropdown in ASP.NET MVC
https://www.codeproject.com/Questions/1194907/Razor-mutliselect-dropdown-set-values-as-selected
* 使用逗號取值
https://www.intertech.com/Blog/selecting-multiple-items-using-select2-in-mvc-5/
###### tags: `程式設計` `C# MVC`