Как сохранить несколько входов в список для отправки на контроллер - PullRequest
0 голосов
/ 15 октября 2019

У меня есть форма с текстовым полем, и когда пользователь пишет в текстовом поле, появляется новая. Когда он отправляет кнопку отправки, я хочу, чтобы значение каждого текстового поля отправлялось контроллеру в виде списка или любого другого объекта, который позволит мне повторить его.

Это моя форма:


@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();
        }

Как сейчас, список прибывает в ноль

1 Ответ

0 голосов
/ 15 октября 2019

Благодаря комментариям, вот как проблема решается: Ввод

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

И как получить список вКонтроллер:

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