0

Изучаю ASP.NET MVC.

В представлении есть форма, поля в которой динамически добавляються с помощью js скрипта. Пытаюсь передать сразу несколько объектов модели из формы в контроллер. Но в контроллере значение List<Product> products равно null.

Модель:

public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int Quantity { get; set; }
    }

Контроллер:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description,Quantity")] List<Product> products)
{
     if (ModelState.IsValid)
     {
          db.Products.AddRange(products);
          db.SaveChanges();
          return RedirectToAction("Index");
     }
     
     return View();
}

Представление:

@model TestExample.Models.Product

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


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

    <div class="form-horizontal">
        <h4>Product</h4>
        <hr />
        @Html.ValidationSummary(true, "Error!", new { @class = "text-danger" })
        <table class="table table_data">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Description)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Quantity)
                </th>
                <th></th>
            </tr>
            <tr class="table_data_plus">
                <td></td>
                <td></td>
                <td></td>
                <td><span class="btn btn-success plus pull-right">+</span></td>
            </tr>
        </table>

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

JS скрипт:

<script>
    // формируем новые поля
    jQuery('.plus').click(function () {
    jQuery('.table_data_plus').before(
    '<tr>' +
    '<td>@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })</td>' +
    '<td>@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })</td>' +
    '<td>@Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })</td>' +
    '<td><span class="btn btn-danger minus pull-right">&ndash;</span></td>' +
    '</tr>'
    );
    });
    // on - так как элемент динамически создан и обычный обработчик с ним не работает
    jQuery(document).on('click', '.minus', function () {
        jQuery(this).closest('tr').remove(); // удаление строки с полями
    });
</script>

Скрипт добавляет инпуты с одинаковыми id. Не понимаю как все это правильно получить в контроллере.

Форма с динамическими полями созданна JS скриптом

2
  • Вот например решение для JS, кажется сама по себе форма не умеет сабмитить инпуты с одинаковыми айдишниками.
    – aepot
    9 авг 2020 в 20:30
  • @aepot в JS совсем не разбираюсь, данный скрипт взят из примера. Если получать данные в контроллере с помощью FormCollection collection - данные приходят. Теперь вопрос в том, как из них построить модель? 10 авг 2020 в 19:04

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.