IList 在 HttpPost 上始终为空

我正在使用此模式将模型绑定到列表,但是当我发布表单时,IList 始终为空。


我以前成功地使用过这种模式。这次和我过去做的有点不同,因为字段是在一个子循环中生成的。不确定这是否是它不起作用的原因。我已经做了很多反复试验,所以我希望有人能看到我做错了什么:


索引视图

@model Collect.ViewModels.JobWorker

@{

    ViewBag.Title = $"{Model.Job.Name} - Workers";

    Layout = "~/Views/Shared/_Layout.cshtml";

}


<h2>@ViewBag.Title</h2>


@using (Html.BeginForm("Update", "Workers"))

{

    @Html.AntiForgeryToken()

    @Html.HiddenFor(model => Model.JobId)

    int z = 0;

    for (int x = 0; x < Model.WorkPeriods.Count; x++)

    {

        <h3>@Model.WorkPeriods[x].StartDate.toIsoDateString() through @Model.WorkPeriods[x].EndDate.toIsoDateString()</h3>

        <div style="display: flex; flex-wrap: wrap;">

            @for (int y = 1; y <= Model.Job.MaximumNumber; y++)

            {

                <div class="panel panel-primary panel-info-1" >

                    <div class="panel-heading">

                        <span class="fa fa-clock-o"></span> Opening @Model.Workers[z].OpeningNumber

                    </div>

                    <div class="panel-body">

                        @Html.DropDownListFor(model => Model.Workers[z].PersonId, 

                       new SelectList(Model.People, "PersonId", "Name"), 

                       htmlAttributes: new { @class = "form-control" })

                    </div>

                </div>

                @Html.HiddenFor(model => Model.Workers[z].Id);

                @Html.HiddenFor(model => Model.Workers[z].JobId);

                @Html.HiddenFor(model => Model.Workers[z].WorkerId);

                @Html.HiddenFor(model => Model.Workers[z].OpeningNumber);

                @Html.HiddenFor(model => Model.Workers[z].StartDate);

                @Html.HiddenFor(model => Model.Workers[z].EndDate);

                z++;

            }

            <div class="panel-info-1" >

                <button type="submit" value="Update" class="btn btn-default">Update</button>

            </div>

        </div>

    }


}


<div>

    @Html.ActionLink("Back to Jobs", "Index", "Jobs")

</div>



眼眸繁星
浏览 157回答 1
1回答

繁花不似锦

基于视图中使用的模型,@model Collect.ViewModels.JobWorker该Update操作期待错误的模型,这就是模型绑定器没有转换它的原因。[HttpPost][ValidateAntiForgeryToken]public ActionResult Update(byte JobId, JobWorker model) {&nbsp; &nbsp; If(ModelState.IsValid) {&nbsp; &nbsp; &nbsp; &nbsp; IList<Dto.Worker> newWorkers = model.Workers;&nbsp; &nbsp; &nbsp; &nbsp; // logic to update is here&nbsp; &nbsp; &nbsp; &nbsp; return RedirectToAction("Index", "Jobs");&nbsp; &nbsp; }&nbsp; &nbsp; return View(model);}
打开App,查看更多内容
随时随地看视频慕课网APP