【问题标题】:How to save multiple inputs in a List to send to controller如何在列表中保存多个输入以发送到控制器
【发布时间】:2023-04-02 21:50:01
【问题描述】:

我有一个带有文本框的表单,当用户在文本框中书写时,会出现一个新的。当他发送提交按钮时,我希望将每个文本框的值作为列表或任何可以让我迭代它的对象发送到控制器。

这是我的表格:


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Escaneado</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.Label("Codigo", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10" id="listaCodigos">
                <input type="text" id="Code0" class="form-control" autofocus />
                <!-- New inputs well be added here-->

            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

动态添加输入的脚本代码

<script type="text/javascript">
        var id = 1;
        $(document).ready(function () {
            $('#listaCodigos').on('input', function () {
                $('<input type=\"text\" id=\"Code' + id + '\" class=\"form-control\"/>').appendTo("#listaCodigos");
                document.getElementById("Code" + id).focus();
                id++;
            });
        });
    </script>

以及控制器方法:

  [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult NewGroupScan(List<String> listaCodigos)
        {
            //Method Logic
            return View();
        }

就像现在一样,列表到达 null

【问题讨论】:

  • 没有名称的输入字段不会被发送到服务器。此外,要发布列表,请为每个输入字段使用相同的名称并在方括号之间使用索引(例如,listaCodigos[0] 等)。
  • 具有名称属性的输入字段将被发送到服务器以发送列表,只需以数组方式使用名称,如name="Code[0]" , name="Code[1]", name="Code[2]"

标签: c# html razor model-view-controller asp.net-mvc-5


【解决方案1】:

感谢 cmets,问题是这样解决的: 输入

<input type="text" name="codesList[0]" id="Code0" class="form-control" autofocus />

插入输入的脚本:

 <script type="text/javascript">
        var id = 1;
        $(document).ready(function () {
            $('#listaCodigos').on('input', function () {
                $('<input type=\"text\" name=\"codesList[' + id + ']\" id=\"Code' + id + '\" class=\"form-control\"/>').appendTo("#listaCodigos");
                document.getElementById("Code" + id).focus();
                id++;
            });
        });
    </script>

以及如何在Controller中获取List:

public ActionResult NewGroupScan(List<String> codesList){...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多