繁体   English   中英

传递给控制器​​时,具有复杂类型的视图模型为null

[英]View model with complex type is null when passed to controller

我试图将复杂类型的视图模型传递给我的控制器。 我已经研究过所有关于这个主题的自上而下的内容,我仍然感到困惑。

问题:

单击我的提交按钮时,将传入视图模型,但是MacroInfo列表属性为null。

UpdateIndexViewModel

public class UpdateIndexViewModel
{
    //This view model will become larger later
    public List<MacroInfo> MacrosToUpdate { get; set; }
}

MacroInfo

public class MacroInfo
{
    public bool IsSelected { get; set; }
    public string FullPath { get; set; }
    public string Id { get; set; }
    public DateTime CreatedAt { get; set; }
}   

控制器动作

[HttpPost]
public ActionResult Submit(UpdateIndexViewModel updateIndexViewModel)
{
    //updateIndexViewModel.MacrosToUpdate is null ??
}

索引视图

@model EplanInterface.Core.ViewModels.UpdateIndexViewModel

@using (Html.BeginForm("Submit", "Update", FormMethod.Post))
{
    <table style="width:100%" , class="table-bordered">
        <thead>
            <tr>
                <th>#</th>
                <th>Macro Path</th>
                <th>Created At</th>
                <th>Update</th>
            </tr>
        </thead>
        @for (int i = 1; i < Model.MacrosToUpdate.Count; i++)
        {
            <tr>
                <td>@Html.TextBoxFor(m =>Model.MacrosToUpdate[i].FullPath)</td>
                <td>@Html.TextBoxFor(m => Model.MacrosToUpdate[i].CreatedAt)</td>
                <td>@Html.CheckBoxFor(b => Model.MacrosToUpdate[i].IsSelected)</td>
            </tr>
        }
    </table>
    <input type="submit" class="btn btn-primary" value="Submit"/>
}

我试过了什么

我尝试将传入的控制器动作属性更改为List<MacroInfo> macrosToUpdate ,但在执行此操作时,该属性仍为null。

Chrome网络检查

在此输入图像描述

最后的评论

我不确定是否需要使用AJAX帖子来执行此操作,或者我的变量名称是否格式不正确。 我很确定这是一个具有约束力的问题,我不理解。

如果有人能指出我正确的方向,我会非常感激。

这部分模板有点不对劲。

@for (int i = 1; i < Model.MacrosToUpdate.Count; i++)
{
    <tr>
        <td>@Html.TextBoxFor(m =>Model.MacrosToUpdate[i].FullPath)</td>
        <td>@Html.TextBoxFor(m => Model.MacrosToUpdate[i].CreatedAt)</td>
        <td>@Html.CheckBoxFor(b => Model.MacrosToUpdate[i].IsSelected)</td>
    </tr>
}

请更改以下内容,然后重试。

@for (int i = 0; i < Model.MacrosToUpdate.Count; 
{
        <tr>
            <td>@i</td>
            <td>@Html.TextBoxFor(m => m.MacrosToUpdate[i].FullPath)</td>
            <td>@Html.TextBoxFor(m => m.MacrosToUpdate[i].CreatedAt)</td>
            <td>@Html.CheckBoxFor(b => b.MacrosToUpdate[i].IsSelected)</td>
        </tr>
 }

首先,你用1开始循环,这是根本原因。 由于缺少第0个索引,模型绑定器无法正确绑定列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM