【问题标题】:IEnumerable Model from view to Controller is NULL [duplicate]从视图到控制器的 IEnumerable 模型为 NULL [重复]
【发布时间】:2018-12-15 05:27:26
【问题描述】:

我正在尝试将视图的表值返回到控制器以保存在 db 上,但我一直为空。我可以毫无问题地发布值并将它们绑定到视图。

我不明白为什么,我使用的是服务器端视图模型。

有什么办法可以做到吗?

查看:

@model  IEnumerable<MultiEdit.Models.TableViewModel>

@using (Ajax.BeginForm("Save", "UUTs", new AjaxOptions
{
    HttpMethod = "Post",

}, new { id = "tableForm" }))
{
    @Html.AntiForgeryToken()
    <div class="row" style="padding-top:10px;">
        <div class="col-lg-12">
            <table class="table table-bordered table-striped ">
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.IsChassis)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Justification)
                        </th>
                    </tr>
                </thead>
                <tbody id="tblMultiEdit">
                    @foreach(var item in Model)
                    {
                        <tr>
                            <td>
                                @Html.CheckBoxFor(modelItem => item.CheckIsChassis)
                            </td>
                            <td>
                                @Html.EditorFor(modelItem => item.Justification)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
}

控制器:

public void Save(IEnumerable<TableViewModel> vm)
        {
            DoSomething();
        }

【问题讨论】:

    标签: ajax asp.net-mvc ienumerable


    【解决方案1】:

    您需要使用 for 循环和索引限定符遍历您的集合。像下面这样的东西。语法不准确,但你应该能明白我的意思。

    @for(var index = 0; index <= Model.Count - 1; index++)
    {
         <tr>
             <td>
                 @Html.CheckBoxFor(modelItem => Model[index].CheckIsChassis)
             </td>
             <td>
                 @Html.EditorFor(modelItem => Model[index].Justification)
             </td>
         </tr>
     }
    

    这是必需的,因此索引可用于创建可枚举项的唯一 ID 并帮助模型绑定

    希望有帮助

    【讨论】:

    • 我不允许我将 [] 应用于 IEnumerable 类型。
    【解决方案2】:

    我通过使用 IList insead 的 IEnumerable 解决了它。

    查看:

    @model IList<MultiEdit.Models.TableViewModel>
    
    @Html.CheckBoxFor(modelItem => modelItem[index].CheckIsChassis, new { @class = "form-control" })
    

    控制器:

    public void Save(IList<TableViewModel> vm)
        {
            var x = vm;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2011-11-22
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      相关资源
      最近更新 更多