我有以下形式,其中包含要发送到服务器的多维数组中的数据。问题是我看不到在我的控制器中获取这些数据。
索引.html
<form id="my-form" action="/Home/TestingMethod" method="post">
<table id="people" class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Owns Item</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Danny</td>
<td class="items">
<select name="PersonList[1]Item[]" class="form-control">
<option value=""></option>
<option value="Keys">Keys</option>
<option value="Phone">Phone</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
我的模型
public class MyModel
{
public List<int> PersonList { get; set; }
}
首页控制器
[HttpPost]
public JsonResult TestingMethod(MyModel model)
{
List<int> list_of_people = model.PersonList;
return Json("I am the server, I got your data.");
}
问题是list_of_people
包含 0 个元素。
提交的表单数据
PersonList[1]Item[]:Phone
相关: 如何在 MVC 控制器中访问 Javascript 多维数组
选择字段的命名约定不正确。为了匹配您的模型结构,它应该如下所示:
<select name="PersonList[0]" class="form-control">
<select name="PersonList[1]" class="form-control">
<select name="PersonList[2]" class="form-control">
...
因为 PersonList
属性只是一个整数数组。如果您希望能够绑定到整数,还要确保发送整数值:
<option value="0">Keys</option>
<option value="1">Phone</option>
...
如果要允许空值,请确保将列表定义为可为空的整数:
public class MyModel
{
public List<int?> PersonList { get; set; }
}
现在你可以这样做:
<option value=""></option>
<option value="0">Keys</option>
<option value="1">Phone</option>
...
另一方面,如果它是一个复杂的属性:
public class MyModel
{
public List<Person> PersonList { get; set; }
}
其中 Person 定义如下:
public class Person
{
public List<Item> Items { get; set; }
}
然后你可以这样做:
<select name="PersonList[0].Items[0].SomeProperty" class="form-control">
<select name="PersonList[0].Items[1].SomeProperty" class="form-control">
<select name="PersonList[1].Items[0].SomeProperty" class="form-control">
...
我还建议您阅读following post
,该解释了模型绑定器的工作原理以及它所期望的命名约定。