在 MVC 5 中如何将 table 对象数据作为列表传递给控制器​​视图模型?

In MVC 5 how to pass table Object data as a list to Controller View Model?

我的控制器 ItemRequestViewModel 为空,问题是它没有将任何值从视图传递到控制器但是当我传递一个 List<string> 它显示一个行值。我只是不能将多个对象传递给 Controllers ViewModel。我也试过作为 List<ItemRequestViewModel reqItem> 传递,但似乎没有希望。

我的控制器

public ActionResult ReqNotifyApprove(List<ItemRequestViewModel> reqItem)
{
   return null;
}

我的看法

@model IEnumerable<Management_System.ViewModels.ItemRequestViewModel>
@using (Html.BeginForm("ReqNotifyApprove", 
                       "RequestedItems", 
                       FormMethod.Post, 
                       new { id = "ReqItemApproveForm" }))
 {
    <table class="table table-bordered results">
        <thead>
            <tr>
                <th>ID</th>
                <th>ITEM ID</th>
                <th>DESCRIPTION</th>
                <th>UOM</th>
                <th>AVL QTY</th>
                <th>REQ QTY</th>
                <th>AUTH QTY</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var item in Model)
        {
        <tr>
            <th>
                @Html.DisplayFor(modelItem => item.Id)
                @Html.HiddenFor(modelItem => item.Id, new { name = "Id" })
            </th>
            <th>
                @Html.DisplayFor(modelItem => item.PDT_CODE)
            </th>
            <td>
                @Html.DisplayFor(modelItem => item.PDT_NAME)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UOM_SNAME)
            </td>

            <td>
                @Html.DisplayFor(modelItem => item.AvailableQty)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ISS_QTY)
            </td>
            <td>
                <input type="number" id="ApprovedQuantity" name="ApprovedQuantity" class="form-control" min="0" style="width: 80px;">
            </td>
        </tr>
        }
        </tbody>
    </table>
<div>
    <input class="btn btn-lg btn-success" type="submit" value="Approve" />
</div>
}

我也已经尝试过不同的数据绑定,但没有希望。

您的方法存在问题,您将固定的名称属性设置为 "Id"。 MVC 绑定集合的方式是将“[index]”作为前缀添加到 HTML name 属性。您可以在此处找到更多详细信息 - https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

因此,如果您删除此 new { name = "Id" },并使用 for 而不是 foreach, 你的剃刀会是这样的:

@for (int i=0; i < Model.Count; i++)
{
    @Html.DisplayFor(modelItem => Model[i].Id)
    @Html.HiddenFor(modelItem => Model[i].Id)
    ....
}

隐藏输入的结果应该是这样的:

<input type='hidden' name="[0].Id" id="0__Id" />
<input type='hidden' name="[1].Id" id="1__Id" />
<input type='hidden' name="[2].Id" id="2__Id" />