【发布时间】:2022-01-19 15:48:19
【问题描述】:
我的观点是 C#:
@{
var itemList = (List<Item>)ViewData["itemsList"];
}
<div class="row" style="margin-top: 10px;">
<div class="col-md-6">
@if (itemList != null)
{
var id = 0;
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th></th>
<th>Id</th>
<th>Type</th>
</tr>
</thead>
<tbody>
@foreach (var result in itemsList)
{
<tr>
<td>@(++id)</td>
<td><input type="checkbox" value="true" @(result.Checked ? "checked" : "")></td>
<td>@result.Id</td>
<td>@result.Type</td>
</tr>
}
</tbody>
</table>
}
<div class="row justify-content-end" style="margin-top: 20px;">
<div class="col-md-2">
<form asp-controller="Control" asp-action="Remove" method="post">
<input type="hidden" name="tableName" value="table"/>
<input type="hidden" name="items" value="@itemList"/>
<div style="margin-left: -10px;" class="col-md-2">
<button class="btn btn-danger" title="Remove" type="submit">Remove</button>
</div>
</form>
</div>
</div>
</div>
</div>
我想从用户选中复选框的表格中删除项目。我的想法是使用列表(result.Checked 属性)更新每个选中的项目,然后将数组发送到 Remove 方法:
[HttpPost]
public async Task<IActionResult> Remove(string tableName, List<ChangeQueueItem> items)
{
try
{
var toDelete = items.Where(x => x.Checked == true);
await _repository.RemoveFromQueue(toDelete, tableName);
}
catch (Exception e)
{
TempData["error"] = e.Message;
}
return RedirectToAction("Index");
}
我正在尝试像这样发送该列表:
<input type="hidden" name="items" value="@itemList"/>
但是该值为空。我该怎么做?
更新:此处加载数据:
[HttpGet]
public async Task<IActionResult> Index()
{
var items = await _repository.GetAll();
ViewData["itemsList"] = items;
ViewData["error"] = TempData["error"];
return View("Index");
}
【问题讨论】:
-
所以你想用
<input type="hidden" name="items" value="@itemList"/>绑定一个列表?输入无法绑定类型为列表的值。你可以尝试使用多个隐藏输入来绑定一个列表。
标签: c# asp.net-mvc asp.net-core razor razor-pages