【问题标题】:Passing data from an HTML form via an array to $_POST通过数组将数据从 HTML 表单传递到 $_POST
【发布时间】:2014-10-30 21:16:04
【问题描述】:

以下是用 ASP.NET Razor 编写的。

我有一个页面,它根据数据库查询的结果在 HTML 表单中动态创建行。结果集中的每一行对应于表单中的一行。每行都有两个输入字段,我需要能够通过 $_POST 传递它们。

foreach (var @row in list) {
    <li>
        <span style="width: 100px; display: inline-block">@row.Name</span>
        <input type="text" name="time[]" />minutes on
        <input type="text" name="date[]" />
    </li>
}

我的期望是我能够像这样访问和迭代数据:

var timeList = Request.Form["time"];
foreach (var time in timeList) {
    // Stuff
}

但这不起作用。我不断收到 timeList 的“对象引用未设置为对象的实例”错误。我想要做的甚至可能吗?知道有什么问题吗?

【问题讨论】:

    标签: html asp.net asp.net-mvc post razor


    【解决方案1】:

    试着去掉你名字中的方括号:

    foreach (var @row in list) {
        <li>
            <span style="width: 100px; display: inline-block">@row.Name</span>
            <input type="text" name="time" />minutes on
            <input type="text" name="date" />
        </li>
    }
    

    循环将创建重复的名称,这些名称在 HTML 中形成数组,因此您可以得到您想要的。但是,我不确定当列表只有一个项目时这是否有效,所以测试一下。

    【讨论】:

      【解决方案2】:

      客户端 HTML:

      <form action="~/Page" method="post">
          <input type="hidden" name="product_0_id" value="0" />
          <input type="text" name="product_0_name" value="Prod. #1" />
          <input type="hidden" name="product_1_id" value="1" />
          <input type="text" name="product_1_name" value="Prod. #2" />
      </form>
      

      服务器:

       string youGroupKey = "product";
       Dictionary<string, string>[] values = Request.Form
           .AllKeys
           .Where(k => k.StartsWith(youGroupKey))
           .GroupBy(k => k
               .Substring(youGroupKey.Length + 1, 1),
                   (a, b) => {
                       return b
                           .ToDictionary(c => c
                               .Substring(youGroupKey.Length + 3), d => Request.Form[d]);
                   }
            )
            .ToArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 2016-10-11
        相关资源
        最近更新 更多