Nie*_* R. 6 c# asp.net-core-mvc .net-core asp.net-core asp.net-core-2.1
我试图弄清楚如何将表单元素绑定到包含数组或可枚举属性的模型。该表单应该可用于添加新对象或编辑现有对象。
下面是一个精简的示例。
如果 Levels 不包含任何元素(例如 create),则不会呈现 Level 字段行。您应该向 Level 数组添加一个空元素还是应该添加一行空字段?但如何使用 asp-for 属性来做到这一点。
如果级别包含元素(例如编辑),则会呈现级别字段的行。但是,当model.Levels在Edit方法中发布时null。
有什么想法如何最好地实现这一点?
要绑定的模型
public class CarparkModel
{
[HiddenInput]
public int Id { get; set; }
public string Name { get; set; }
public Level[] Levels { get; set; }
}
public class Level
{
[HiddenInput]
public int Id { get; set; }
public string Description { get; set; }
public int NrOfSpaces { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
主视图
@model CarparkModel
<form method="POST">
<input asp-for="Id">
<div>
<label asp-for="Name"></label>
<input asp-for="Name">
</div>
<table>
<tr>
<th>Description</th>
<th>Nr of spaces</th>
</tr>
@foreach (Level level in Model.Levels)
{
<tr>
<td><input asp-for="Description"></td>
<td><input asp-for="NrOfSpaces"></td>
</tr>
}
<tr>
<td colspan="2>
<!-- Click = new row of Level fields added -->
<button type="button">Add level</button>
</td>
</tr>
</table>
<button type="submit">Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)
控制器
public class CarparkController
{
[HttpGet]
public IActionResult Create()
{
return View(new CarparkModel());
}
[HttpPost]
public IActionResult Create(CarparkModel model)
{
if (ModelState.IsValid)
{
_repository.Save(model);
return RedirectToAction("index");
}
return View(model);
}
[HttpGet]
public IActionResult Edit(int id)
{
return View(_repository.Get(id));
}
[HttpPost]
public IActionResult Edit(CarparkModel model)
{
if (ModelState.IsValid)
{
_repository.Save(model);
return RedirectToAction("index");
}
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
foreach如果您希望能够以表单形式将项目发回,请不要使用。使用for带有项目索引命名的循环。
@model CarparkModel
<form method="POST">
<input asp-for="Id">
<div>
<label asp-for="Name"></label>
<input asp-for="Name">
</div>
<table>
<tr>
<th>Description</th>
<th>Nr of spaces</th>
</tr>
@for(var index = 0, index < Model.Levels.Length, index++)
{
<tr>
<td><input asp-for="@Model.Levels[index].Description"></td>
<td><input asp-for="@Model.Levels[index].NrOfSpaces"></td>
</tr>
}
<tr>
<td colspan="2">
<!-- Click = new row of Level fields added -->
<button type="button">Add level</button>
</td>
</tr>
</table>
<button type="submit">Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)
在表单中发布集合时需要索引来重建集合。
| 归档时间: |
|
| 查看次数: |
10678 次 |
| 最近记录: |