[英]form for a model that contains a list property in asp.net core 3 MVC
我正在尝试在 asp.net core 3 MVC 中创建一个表单。
the model is a "package" class that contains different properties about the package, and a List<item> items
property of the items in the package, item is a class defined that contains different properties of an "item".
我应该如何为用户创建一个表单来添加一个新的“包”?
加上在其中插入项目,可以是任意数量的项目,我希望用户为每个项目插入一行(带有一个为新项目添加新输入行的按钮)并与最终表单一起提交。
任何帮助,将不胜感激。
这是一个完整的工作演示:
Model:
public class Package
{
public int Id { get; set; }
public string Name { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public int Id { get; set; }
public string ItemName { get; set; }
}
看法:
@model Package
<h1>Create</h1>
<h4>Package</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button onclick="addRow()" type="button">Add Row</button>
<table id="AddItemsTable">
<tr>
<th>@Html.DisplayNameFor(model=>model.Items[0].ItemName)</th>
</tr>
</table>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
JS:
@section Scripts {
<script>
var counter = 0;
function addRow() {
var table = document.getElementById("AddItemsTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text" name="Items[' + counter+'].ItemName"/>';
counter++;
}
</script>
}
Controller:
// GET: Packages/Create
public IActionResult Create()
{
return View();
}
// POST: Packages/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Package package)
{
if (ModelState.IsValid)
{
_context.Add(package);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(package);
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.