I have view is C#:
@{
var itemList = (List<Item>)ViewData["itemsList"];
}
<div style="margin-top: 10px;">
<div >
@if (itemList != null)
{
var id = 0;
<table >
<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 style="margin-top: 20px;">
<div >
<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;" >
<button 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:
[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. 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");
}
CodePudding user response:
First, you set value using ViewData["itemsList"] = items;
, but get it by var itemList = (List<Item>)ViewData["itemList"];
.
Change key value to be consistent: for example, replace itemList
by itemsList
in the view.
Second, to pass list from the view to the controller action method apply indexes to the items:
<tbody>
@using (Html.BeginForm("Remove", "Control"))
{
@Html.Hidden("tableName", "table")
@for (int i = 0; i < itemsList.Count; i )
{
@Html.Hidden("items[" i "].Id", itemsList[i].Id)
@Html.Hidden("items[" i "].Type", itemsList[i].Type)
<tr>
<td>@( id)</td>
<td>@Html.CheckBox("items[" i "].Checked", itemsList[i].Checked)</td>
<td>@itemsList[i].Id</td>
<td>@itemsList[i].Type</td>
</tr>
}
<tr><td><button title="Remove" type="submit">Remove</button></td></tr>
}
</tbody>
CodePudding user response:
It doesn't appear that you're setting the TempData["itemList"]
; I can't see it in the code.
You should be setting it using something like:
TempData["itemList"] = toDelete;