1

I have this view containing a list of objects, this objects can be edited and etc and is stored in a session. If all objects are correct, user can submit it to save it to db. My problem is the controller always accepts null value

Here is my view

    @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>

Here is my controller code:

[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();
        }
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • 1
    `@foreach (var item in Model)` possibly becomes the issue. Use `for` loop with indexes to bind with `List` argument in POST method. – Tetsuya Yamamoto Aug 07 '18 at 08:20
  • And you don't even have any form controls, so there is nothing to post back anyway (its not clear what the point of this is when nothing is editable) –  Aug 07 '18 at 08:32

0 Answers0