Sve*_*art 9 arrays asp.net-mvc http-post asp.net-mvc-5
我该如何处理输入数组
例如我在我看来:
<input type="text" name="listStrings[0]" /><br />
<input type="text" name="listStrings[1]" /><br />
<input type="text" name="listStrings[2]" /><br />
Run Code Online (Sandbox Code Playgroud)
在我的控制中,我试着获得如下值:
[HttpPost]
public ActionResult testMultiple(string[] listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
在调试,我可以看到listStrings的null每一次.
为什么它为null,如何获取输入数组的值
Nic*_*ick 17
要发布基元集合,输入必须具有相同的名称.这样,当您发布表单时,请求的正文将会是这样的
listStrings=a&listStrings=b&listStrings=c
Run Code Online (Sandbox Code Playgroud)
MVC将知道,由于这些参数具有相同的名称,因此应将它们转换为集合.
所以,将表单更改为这样
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
Run Code Online (Sandbox Code Playgroud)
我还建议将控制器方法中的参数类型更改ICollection<string>为a而不是a string[].所以你的控制器看起来像这样:
[HttpPost]
public ActionResult testMultiple(ICollection<string> listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您想发布更复杂对象的集合,请说明ICollection<Person>您对该Person类的定义
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
那么你在原始形式中使用的命名约定就会发挥作用.由于现在需要多个表示不同属性的输入来发布整个对象,因此只需命名具有相同名称的输入就没有意义.您必须指定输入在名称中指定的对象和属性.为此,您将使用命名约定collectionName[index].PropertyName.
例如Age,a 的属性的输入Person可能具有类似的名称people[0].Age.
ICollection<Person>在这种情况下用于提交的表单如下所示:
<form method="post" action="/people/CreatePeople">
<input type="text" name="people[0].Name" />
<input type="text" name="people[0].Age" />
<input type="text" name="people[1].Name" />
<input type="text" name="people[1].Age" />
<button type="submit">submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
期望请求的方法看起来像这样:
[HttpPost]
public ActionResult CreatePeople(ICollection<Person> people)
{
//Do something with the people collection
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6255 次 |
| 最近记录: |