将动态生成的文本框值发送到C#Controller?

时间:2016-10-27 14:46:18

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

所以我有一个像这样工作的表: 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中的对象?)< / p>

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

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

1 个答案:

答案 0 :(得分:2)

如果您遇到某些条件,MVC Modelbinder将能够直接绑定POST数据:

  • 动态添加的HTML输入的名称和ID符合MVC使用的命名方案。即要绑定集合的第一个元素,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]">

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

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

相关问题