这篇调整的方向是
Controller 新增 Action :
[HttpPost, Route("api/[controller]/[action]")]
public IActionResult AddOrderItem([FromForm]int index)
{
ViewData["OrderItemIndex"] = index;
return PartialView("/Views/Day14/OrderItem.cshtml", new OrderItem() );
}
说明:
内容:
@using (Html.BeginForm(FormMethod.Post, htmlAttributes: new { autocomplete = "off" }))
{
<p>
@Html.LabelFor(model => model.OrderDate)
@Html.EditorFor(m => m.OrderDate)
</p>
<div>
@Html.LabelFor(model => model.Items)
<table>
<thead>
<tr>
<th>@Html.LabelFor(m => m.Items.FirstOrDefault().Name)</th>
<th>@Html.LabelFor(m => m.Items.FirstOrDefault().Quantity)</th>
<th>
<button type="button"
onclick="AddItem()">
新增
</button>
</th>
</tr>
</thead>
<tbody id="Items">
@for (int i = 0; i < Model?.Items?.Length; i++)
{
ViewData["OrderItemIndex"] = i;
@Html.Partial("OrderItem", Model?.Items[i], ViewData)
}
</tbody>
</table>
</div>
<p>
<button type="submit">送出</button>
</p>
}
<p>
<a asp-action="Index">回上一层</a>
</p>
@section Scripts
{
<script>
window.ItemsCount = @(Model?.Items?.Length ?? 0);
window.AddItemUrl = '@Url.Action("AddOrderItem")';
window.AddItem = function () {
const requestBody = new URLSearchParams();
requestBody.append('index', ItemsCount);
fetch(AddItemUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: requestBody,
})
.then(response => response.text())
.then(data => {
$('#Items').append(data);
ItemsCount++;
})
}
window.DeleteItem = function (e) {
const btnDom = e.target;
const trDom = $(btnDom).parent().parent();
trDom.remove();
}
</script>
}
Partial View OrderItem.cshtml
说明:
内容:
@model Project.Models.Day14.OrderItem
@{
var itemIndex = ViewData["OrderItemIndex"];
}
<tr>
@Html.Hidden("Items.index", itemIndex)
<td>
@Html.TextBox($"Items[{itemIndex}].Name", Model.Name)
</td>
<td>
@Html.TextBox($"Items[{itemIndex}].Quantity", Model.Quantity, new { type = "number", step = 1, min = 0 })
</td>
<td>
<button type="button"
onclick="DeleteItem(event)">
删除
</button>
</td>
</tr>
实际执行後,不管如何动态新增/删除,在 submit 後,都可以确实传递页面上的资料 !
与上一篇文章的范例相比
这篇先到这里,下一篇来看 Tag Helper 的部份 !
<<: Day06 Kibana - Discover Search
接着要示范如何用 Eloquent 建立多对多关联的查询,目标帮目前的 Todo 建立 Tag 标签...
大家好,我是YIYI,今天我要来回覆身边的朋友们看完我的文章後问我的问题。 QA Q:如果重来一次还...
今天我们将来了解 S3 与 EBS 这两种储存方案的各自特点,并为大家介绍 AWS S3 在整体架...
为什麽需要定位元素? 定位元素可以实现 : 某个元素可以自由地在一个盒子内移动位置,并且压住其他盒子...
金鱼都能懂的网页切版:26、27 版面组合 https://codepen.io/mikeyam/p...