如何处理输入数组
例如我在我看来:
<input type="text" name="listStrings[0]" /><br />
<input type="text" name="listStrings[1]" /><br />
<input type="text" name="listStrings[2]" /><br />
在我的控制中,我尝试获得如下值:
[HttpPost]
public ActionResult testMultiple(string[] listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
在调试时,我每次都可以看到listStrings
为null
。
为什么它为null,如何获取输入数组的值
答案 0 :(得分:17)
要发布基元集合,输入必须具有相同的名称。这样,当您发布表单时,请求的正文将如下所示
listStrings=a&listStrings=b&listStrings=c
MVC将知道,由于这些参数具有相同的名称,因此应将它们转换为集合。
所以,将表单更改为这样
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
我还建议您将控制器方法中的参数类型更改为ICollection<string>
而不是string[]
。所以你的控制器看起来像这样:
[HttpPost]
public ActionResult testMultiple(ICollection<string> listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
现在,如果您想发布更复杂对象的集合,请说明ICollection<Person>
类定义的Person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
然后您在原始表单中使用的命名约定将起作用。由于现在需要多个表示不同属性的输入来发布整个对象,因此只需命名具有相同名称的输入就没有意义。您必须指定输入在名称中指定的对象和属性。为此,您将使用命名约定collectionName[index].PropertyName
。
例如,Age
的{{1}}属性的输入可能具有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>