带有 Html.BeginCollectionItem 扩展名的 MVC 嵌套 EditorTemplate 总是 returns 值设置为“0”或 'null' 的对象

MVC nested EditorTemplate with Html.BeginCollectionItem extension always returns an object with values set to '0' or 'null'

我正在尝试 return 一个包含一个或多个子模型的模型,而子模型又可以包含一个子模型。第一层 return 成功,但是,当我想要 return 子模型的第三层时,我得到了该模型的 'default' 实例,但没有实际填充的变量。因此,模型 returned 包含一个子模型,子模型包含另一个子模型,但最后一个子模型的值设置为 '0' 和 'null'.

我正在使用 Html.BeginItemCollection 扩展方法,但我不确定我是否在第 3 层以正确的方式使用它们。如果有人愿意看一下并帮助我吗?

主模型页面(第 1 层)

@using Website.Models
@model CreateAgendaBindingModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
    <div class="form-horizontal">   
    for (int i = 1; i < 16; i++)
    {
        <div id='CreateVoedingDiv_@i'>
              @Html.EditorFor(x => x.VoedingCollection[i], "CreateVoedingTemplate")
        </div>
    }
}

主模型class(第1层)

public class CreateAgendaBindingModel
{
    public int Id { get; set; }
    public List<CreateVoedingBindingModel> VoedingCollection { get; set; }
}

子模型页面(第2层)

@using HtmlHelpers.BeginCollectionItem;
@using Website.Models

@model CreateVoedingBindingModel

@using (Html.BeginCollectionItem("VoedingCollection"))
{
    <div class="form-group" id=@customVoedingId>
            @Html.EditorFor(x => x.CustomVoeding[0], "CreateCustomVoedingTemplate")
    </div>
}

子模型class(第 2 层)

public class CreateVoedingBindingModel
{
    public int Id { get; set; }
    public List<customvoeding> CustomVoeding { get; set; }
}

子模型页面的子模型(第3层)

@using HtmlHelpers.BeginCollectionItem;
@model FoodtrackerModel.customvoeding

@using (Html.BeginCollectionItem(ViewData.TemplateInfo.HtmlFieldPrefix + ".CustomVoeding"))
{
    <div class="form-group">
        @Html.Label("Opmerking (optioneel)", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.customVoedingOpmerking, new { htmlAttributes = new { @class = "form-control" } })                   
        </div>
    </div>
}

子模型class的子模型是与Entity Framework集成的部分class。

子模型的子模型class(第3层)

public partial class customvoeding
{
    public static List<customvoeding> GetAllCustomvoeding()
    {
        using (foodtrackerEntities1 db = new foodtrackerEntities1())
        {
            db.Configuration.LazyLoadingEnabled = false;
            return db.customvoeding.ToList();
        }
    }
}

所以澄清一下,第 1 层和第 2 层 return 填充了所有变量。第 3 层 return 编辑但未填充任何变量。

我通过不使用子模型的子模型解决了我的问题。我只是简单地将子模型字段的子模型硬编码为上一层的字段(因此第 3 层字段成为第 2 层字段)。恶心,但它解决了我的问题。老实说,我不理解在短时间内提供的解决方案,因为时间就是金钱,所以我继续。

对 MVC 默认没有此功能感到失望。