Asp.net mvc 4 ASP.NET MVC 4-嵌套集合的EditorTemplate

Asp.net mvc 4 ASP.NET MVC 4-嵌套集合的EditorTemplate,asp.net-mvc-4,mvc-editor-templates,Asp.net Mvc 4,Mvc Editor Templates,我有以下模型类(为解决此问题而简化的类): 它呈现一个EditorTemplate,如下所示: @模型MyNamespace.exerciseForPullow @using (Html.BeginForm("ScoreExercise", "SharedLesson", FormMethod.Post)) { @Html.Hidden("Id", Model.Id) @if (Model.ExerciseItems != null) {

我有以下模型类(为解决此问题而简化的类):

它呈现一个EditorTemplate,如下所示: @模型MyNamespace.exerciseForPullow

@using (Html.BeginForm("ScoreExercise", "SharedLesson", FormMethod.Post))
{
    @Html.Hidden("Id", Model.Id)
    @if (Model.ExerciseItems != null)
        {
            foreach (var exerciseItem in Model.ExerciseItems)
                {
                        @Html.EditorFor(x => exerciseItem, "ExerciseItemForPupil")
                }
        }
    <input type="submit" value="Submit"/>
}
问题: 如图所示,页面上将有多个表单。我的“得分练习”动作如下:

public ActionResult ScoreExercise(ExerciseForPupil exercise)
{
    //exercise.ExerciseItems is NULL
}
@Html.EditorFor(x => x.Lesson.Exercises)
但是我的第二层嵌套集合(ExerciseItems)为null。 我做错了什么

更新 我已经根据@MysterMan建议更改了代码: 我调用编辑器模板进行如下练习:

public ActionResult ScoreExercise(ExerciseForPupil exercise)
{
    //exercise.ExerciseItems is NULL
}
@Html.EditorFor(x => x.Lesson.Exercises)
在这个编辑器模板中,我为我的练习项调用编辑器模板

@Html.EditorFor(x=>x.ExerciseItems)
这将呈现UserValue属性的以下标记:

<input id="Lesson_Exercises_0__ExerciseItems_1__UserValue" name="Lesson.Exercises[0].ExerciseItems[1].UserValue" type="text" value="">


但是它也不起作用

不要使用foreach。如果将集合传递给EditorTemplates,则它已在集合上迭代

@model MyNamespace.ExerciseForPupil

@using (Html.BeginForm("ScoreExercise", "SharedLesson"))
{
    @Html.HiddenFor(x => x.Id)
    @Html.EditorFor(x =>  x.ExerciseItemsForPupil)
    <input type="submit" value="Submit"/>
}
@model MyNamespace.exerciseforpull
@使用(Html.BeginForm(“ScoreExercise”、“SharedLesson”))
{
@Html.HiddenFor(x=>x.Id)
@EditorFor(x=>x.ExerciseItemsForPupil)
}
有几件事需要注意。您不必传递模板名称,因为模板名称已经与项目类型相同。您不必使用Post-formmethod,因为这是默认方法。列表中没有属性的名称,所以我假设它是复数形式


您的最后一个类也是非法的,您不会将其指定为那样的列表。

当然,我的最后一个类是非法的。那只是我的错误。但是谢谢你指出这一点out@PiotrPtak-您在exerciseForStool和Lesson中也有错误,每个中的最后一个属性没有属性名称。关键是,如果您没有提供有效的代码,我必须对一些事情做出假设。这些假设可能是正确的,也可能是不正确的,所以请努力提供实际有效的代码。我更新了我的问题。我还摆脱了foreach,并将集合传递给我的编辑器模板,但它不起作用also@PiotrPtak-您的代码仍然有错误,exerciseForStudior的最后一个属性仍然没有属性名称。这个“简化”示例的问题在于,您的实际代码可能正在做一些其他有意义的事情,但是由于您没有包含实际代码,我们只能告诉您示例代码的错误。顺便问一下,您的ScoreExecution方法中是否有
[HttpPost]
属性?是的,我的ScoreExecution方法中有[HttpPost]属性
@model MyNamespace.ExerciseForPupil

@using (Html.BeginForm("ScoreExercise", "SharedLesson"))
{
    @Html.HiddenFor(x => x.Id)
    @Html.EditorFor(x =>  x.ExerciseItemsForPupil)
    <input type="submit" value="Submit"/>
}