首页 > 解决方案 > 如何使用列表正确发布从视图到控制器?

问题描述

我有这个包含对象列表的视图,可以编辑这些对象等,并存储在会话中。如果所有对象都正确,用户可以提交它以将其保存到数据库。我的问题是控制器总是接受空值

这是我的看法

    @model IEnumerable<QnE_Accounting.Models.TransactionsViewModel.BooksViewModel>

<div class="row">
    <form asp-action="Create" method="post" role="form">
        <table class="table">
            <thead>
                <tr>
                    <!--some code here-->
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        @*<td>
                            @Html.DisplayFor(modelItem => item.Id)
                        </td>*@
                        <td>
                            @Html.DisplayFor(modelItem => item.Year)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Month)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Document_Code)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Document_Reference_Number)
                        </td>
                        <!--some code here-->
                        <td>
                            <a asp-action="EditEntry" asp-route-id="@item.Id"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> |
                            <a asp-action="DetailsEntry" asp-route-id="@item.Id"><span class="glyphicon glyphicon-file" aria-hidden="true"></span></a> |
                            <a asp-action="DeleteEntry" asp-route-id="@item.Id"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <div class="form-group">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </form>
</div>
<div>
    <a asp-action="Index">Back to List</a>
</div>

这是我的控制器代码:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(List<BooksViewModel> viewModel)
        {
            if (ModelState.IsValid)
            {
                var list = viewModel;
                //some code here
                return RedirectToAction(nameof(Index));
            }
            return View();
        }

标签: asp.netasp.net-coreasp.net-core-mvc

解决方案


推荐阅读