【问题标题】:Sending dynamically generated textbox values to C# Controller?将动态生成的文本框值发送到 C# 控制器?
【发布时间】:2016-10-27 14:46:17
【问题描述】:

所以我有一个这样工作的表: https://gfycat.com/WeakBlueIslandwhistler

生成者:

<table class="table table-bordered table-with-button table-condensed " id="hidTable">
                            <thead>
                            <tr>
                                <th>HID #</th>
                                <th>Lines</th>
                            </tr>
                            </thead>
                            @for (int j = 0; j < 3; j++)
                            {
                                <tr>
                                    <td>
                                        <input class="form-control table-with-button" type="number" placeholder="HID" id="hid-@j">
                                    </td>
                                    <td>
                                        <input class="form-control table-with-button" type="number" placeholder="Lines" id="lines-@j">
                                    </td>
                                </tr>
                            }
 </table>

通过调用 javascript 方法创建新行和文本框。

本质上,这个表中有未知数量的文本字段对,数据对需要传递给控制器​​...(我在考虑将其作为对象存储在 tempdata 中?)

每个文本框都有一个唯一的 id(分别是 hid-1、hid-2、hid-3 和 lines-1、lines-2、lines-3)

迭代这些文本框、保存它们的值(我可以在保存之前处理验证)然后将其传递到后端的最佳方法是什么?

【问题讨论】:

  • 请注意,您的代码将永远无法正确进行双向绑定,您需要一个具有 2 个属性(int Hidint Line)的模型集合,然后正确生成视图并允许正确的绑定和验证,参考this answer

标签: javascript c# forms razor asp.net-mvc-5


【解决方案1】:

如果满足一些条件,MVC Modelbinder 将能够直接绑定 POST 数据:

  • 动态添加的 HTML 输入的名称和 ID 符合 MVC 使用的命名方案。 IE。要绑定集合的第一个元素,html id 属性的值应为{collectionName}_0name 属性的值应为{collectionName}[0]
  • ViewModel 包含输入列表可以绑定到的集合。

因此,在您的情况下,定义一个包含 HID 和线路列表的 ViewModel

public class PostDataModel {
    public ICollection<int> Hids { get; set; }
    public ICollection<int> Lines { get; set; }
}

然后确保添加附加行的javascript代码正确设置idname

为第 0 行生成的输入应如下所示:

<input class="form-control table-with-button" type="number" placeholder="HID" id="Hids_0" name="Hids[0]">
<input class="form-control table-with-button" type="number" placeholder="Lines" id="Lines_0" name="Lines[0]">

如果用户可以在提交之前删除任何行,请注意non sequential indices

然后只需使用普通 POST 提交表单并使用其索引关联 HID 和行。

【讨论】:

  • 哇,谢谢,效果很好!这种行为是特定于收藏的还是可以用于其他收藏类型? (出于好奇,真的-我坚持使用您的解决方案。)假设我在某个时候想要索引。
  • 你不需要索引器,因为它是一个简单值的集合(索引器只需要复杂对象的集合,它可以简单地是&lt;input class="..." type="number" placeholder="HID" name="hids"&gt;id 属性是不必要的)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 2015-12-01
  • 2016-06-01
相关资源
最近更新 更多