数组 – 发布字符串数组
|
我该如何处理输入数组 例如我在我看来: <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,如何获取输入数组的值 解决方法使用ASP.NET MVC发布基元集合要发布基元集合,输入必须具有相同的名称.这样,当您发布表单时,请求的正文将会是这样的 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>而不是字符串[].所以你的控制器看起来像这样: [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. 例如,Person的Age属性的输入可能具有类似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>
期望请求的方法看起来像这样: [HttpPost]
public ActionResult CreatePeople(ICollection<Person> people)
{
//Do something with the people collection
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 尝试使用asp.net流式传输PDF文件会产生“损坏的文
- asp.net-mvc – ASP.NET MVC – 结合Json结果与V
- asp.net-web-api2 – Swagger中的数据注释
- asp.net-mvc-3 – 在MVC3中对Webgrid行进行内联编
- 过期输出缓存ASP.Net MVC
- asp.net-web-api – 如何在Web Api调用期间获取用
- asp.net-mvc – 操作可能会破坏运行时的稳定性:
- ASP.NET MVC用户 – 您是否想念WebForms中的任何
- asp.net-mvc – Web项目需要使用Razor语法3.0.0.
- 在ASP.NET MVC中使用Razor创建可重用的HTML视图组
