【问题标题】:ASP.NET MVC 4 - EditorTemplate for nested collectionsASP.NET MVC 4 - 嵌套集合的 EditorTemplate
【发布时间】:2013-04-28 20:21:32
【问题描述】:

我有以下模型类(为本问题的目的简化了类):

public class Lesson
{
    public Guid Id {get;set;}
    public string Name {get;set;}
    public List<ExerciseForPupil> Exercises {get;set;}

}
public class ExerciseForPupil
{
    public Guid Id {get;set;}
    public string Name {get;set;}
    public List<ExerciseItemForPupil> ExerciseItems {get;set;}
}
public class ExerciseItemForPupil
{
    public Guid Id {get;set;}
    public string Content {get;set;}
    public string UserValue {get;set;}
}

现在,我希望用户能够为课程中的每个练习填写“UserValue”值。 假设本课有 5 个练习。 我将这些练习呈现如下

@Html.EditorFor(x=>x.Lesson.Exercises)

它会呈现如下所示的 EditorTemplate: @model MyNamespace.ExerciseForPupil

@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"/>
}

我还有“ExerciseItemForPupil”的 EditorTemplate:

@model MyNamespace.ExerciseItemForPupil
@Html.HiddenFor(model => model.Id)
@Html.TextBoxFor(model => model.UserValue)

问题: 可以看出,页面上会有多个表单。我的“ScoreExercise”动作如下:

public ActionResult ScoreExercise(ExerciseForPupil exercise)
{
    //exercise.ExerciseItems is NULL
}

但我在第二级 (ExerciseItems) 上的嵌套集合为空。 我做错了什么?

更新 我已经根据@MysterMan 的建议更改了代码: 我将练习的编辑器模板称为:

@Html.EditorFor(x => x.Lesson.Exercises)

在此 EditorTemplate 中,我为我的锻炼项目调用编辑器模板

@Html.EditorFor(x=>x.ExerciseItems)

这会为 UserValue 属性呈现以下标记:

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

但它也不起作用

【问题讨论】:

    标签: asp.net-mvc-4 mvc-editor-templates


    【解决方案1】:

    不要使用 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"/>
    }
    

    有几点需要注意。您不必传递模板名称,因为模板名称已经与项目类型同名。您不必使用 Post 表单方法,因为这是默认设置。 List 没有属性名称,所以我假设它是复数形式。

    你的最后一堂课也是非法的,你不会把它指定为这样的列表。

    【讨论】:

    • 当然我的最后一节课是非法的。那只是我的错误。但是感谢您指出这一点
    • @PiotrPtak -您在ExerciseForPupil 和Lesson 中也有错误,每个中的最后一个属性都没有属性名称。关键是,如果您不提供有效代码,我必须对事情做出假设。这些假设可能正确,也可能不正确,因此请努力提供实际有效的代码。
    • 我更新了我的问题。我也摆脱了 foreach 并将集合传递给我的编辑器模板,但它也不起作用
    • @PiotrPtak - 您的代码仍然有错误,ExerciseForPupil 的最后一个属性仍然没有属性名称。这个“简化”示例的问题在于您的真实代码可能正在做一些其他的事情,但由于您没有包含您的真实代码,我们只能告诉您您的示例代码有什么问题。顺便问一下,您的 ScoreExercise 方法中有 [HttpPost] 属性吗?
    • 是的,我的 ScoreExercise 方法中有 [HttpPost] 属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2015-06-22
    • 2012-04-10
    相关资源
    最近更新 更多