[英]Return ViewData from view to controller razor pages
I have view is C#:我的观点是 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>
I want to remove items from table, where user checks the checkbox.我想从表中删除项目,用户选中复选框。 My idea was to update each checked item withing the list ( result.Checked
property) and then send array to Remove method:我的想法是使用列表( 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");
}
I am trying to send that list like this:我正在尝试像这样发送该列表:
<input type="hidden" name="items" value="@itemList"/>
however the value is null.但是该值为 null。 How should I do it?我该怎么做?
Update: data is loaded here:更新:数据在这里加载:
[HttpGet]
public async Task<IActionResult> Index()
{
var items = await _repository.GetAll();
ViewData["itemsList"] = items;
ViewData["error"] = TempData["error"];
return View("Index");
}
Ummm where do you send the TempData["itemList"]?, i can't see it in the code.嗯,您将 TempData["itemList"] 发送到哪里?,我在代码中看不到它。
Something like: TempData["itemList"] = toDelete;类似于: TempData["itemList"] = toDelete;
You set value using ViewData["itemsList"] = items;
您使用ViewData["itemsList"] = items;
设置值, but get it by var itemList = (List<Item>)ViewData["itemList"];
,但通过var itemList = (List<Item>)ViewData["itemList"];
. .
Change key value to be consistent: for example, replace itemList
by itemsList
in the view.更改键值以保持一致:例如,将视图中的itemsList
替换为itemList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.