Как передать масив объектов из формы представления в контроллер?
Изучаю 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">–</span></td>' +
'</tr>'
);
});
// on - так как элемент динамически создан и обычный обработчик с ним не работает
jQuery(document).on('click', '.minus', function () {
jQuery(this).closest('tr').remove(); // удаление строки с полями
});
</script>
Скрипт добавляет инпуты с одинаковыми id. Не понимаю как все это правильно получить в контроллере.
