加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

数组 – 发布字符串数组

发布时间:2020-12-16 04:14:49 所属栏目:asp.Net 来源:网络整理
导读:我该如何处理输入数组 例如我在我看来: input type="text" name="listStrings[0]" /br /input type="text" name="listStrings[1]" /br /input type="text" name="listStrings[2]" /br / 在我的控制中,我试图获得如下值: [HttpPost]public ActionResult tes
我该如何处理输入数组

例如我在我看来:

<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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读