Try   HackMD

C# MVC Controller 收Post進來的多筆資料(使用List)

實作上常常需要用一次收多筆資料給Controller,因為input可能是動態產生的

這邊附上可執行範例,底下逐一說明 https://dotnetfiddle.net/5ryBVA

範例程式碼


input區域

<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的型態一次全部收起來

[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

<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

public Guid[] SelectOption { get; set; }

Controller

[HttpPost] public ActionResult Index(Guid[] postback) { return View(); }

Model的名稱必須跟select的name屬性相同,post回來才接得上


參考文件

tags: 程式設計 C# MVC