提问者:小点点

将ViewData从视图返回到控制器剃刀页面


我有视图是C#:

@{
    var itemList = (List<Item>)ViewData["itemList"];
}
<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 itemList)
                    {
                        <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>

我想从表中删除项目,其中用户检查复选框。我的想法是更新每个检查项目与列表(结果。检查属性),然后将数组发送到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");
        }

我正试图发送这样的列表:

但是,该值为空。我该怎么做?

更新:数据在此处加载:

[HttpGet]
        public async Task<IActionResult> Index()
        {
             var items = await _repository.GetAll();
             
            ViewData["itemsList"] = items;
            ViewData["error"] = TempData["error"];

            return View("Index");
        }

共1个答案

匿名用户

嗯,您将TempData[“itemList”]发送到哪里?,我在代码中看不到它。

类似于:TempData[“itemList”]=toDelete;