如何将逗号分隔的值列表绑定到List <...>

Ine*_*nez 2 asp.net-mvc

假设我有一个名为Customers的字段

<input type="text" name="Customers"
Run Code Online (Sandbox Code Playgroud)

我想输入逗号分隔的客户ID,然后在ASP.NET MVC端作为List接收它.这个功能是否构建在ASP.NET MVC中,如果不是最好的方法呢?

Pet*_*ter 5

制作逗号分隔字符串的列表:

var myList = mytextbox.text.Split(',').ToList();  
Run Code Online (Sandbox Code Playgroud)


hac*_*sid 5

你可以有一个模型绑定器进行拆分(如Peter提到的),或者你可以使用JavaScript为所有值添加具有相同名称的隐藏字段.就像是:

<input type="hidden" name="customers" value="102" />
<input type="hidden" name="customers" value="123" />
<input type="hidden" name="customers" value="187" />
<input type="hidden" name="customers" value="298" />
<input type="hidden" name="customers" value="456" />
Run Code Online (Sandbox Code Playgroud)

然后你的动作将采用int的可枚举:

public ActionResult DoSomethingWithCustomers(IEnumerable<int> customers){....}
Run Code Online (Sandbox Code Playgroud)