使用HTML Helper访问子模型

时间:2014-02-07 05:40:38

标签: asp.net-mvc razor linq-to-entities html-helper

我有一个看起来像这样的对象:

public class QuestionSet
{
    [Required]
    public int Id { get; set; }

    [Required]
    public int ConferenceId { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<RegistrationQuestion> Questions { get; set; }

    public virtual ICollection<QuestionSetAssignee> QuestionSetAssignees { get; set; }

    public QuestionSet()
    {

    }

    public QuestionSet(int conferenceId)
    {
        this.ConferenceId = conferenceId;
    }
}

RegistrationQuestion的模型如下所示:

public class RegistrationQuestion
{
    [Required]
    public int Id { get; set; }

    [Required]
    public int QuestionSetId { get; set; }

    [Required]
    public string QuestionText { get; set; }
}

创建QuestionSet时,我想同时创建其相关的RegistrationsQuestions。但是,Razor Html Helpers不会让我深入到那个级别。

我可以这样做:

@Html.LabelFor(model => model.Questions)

但不是这个(这是我希望能够做到的):

@Html.LabelFor(model => model.Questions.QuestionText)

有关如何实现这一目标的任何指导?

2 个答案:

答案 0 :(得分:0)

你可以让它像这样工作。我对您的模型进行了少量更改,而不是使用ICollection&lt;&gt;,我使用了IList&lt;&gt;它具有索引器支持,可以轻松迭代。

public class QuestionSet
{
    [Required]
    public int Id { get; set; }

    [Required]
    public int ConferenceId { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual IList<RegistrationQuestion> Questions { get; set; }
}

public class RegistrationQuestion
{
    [Required]
    public int Id { get; set; }

    [Required]
    public int QuestionSetId { get; set; }

    [Required]
    public string QuestionText { get; set; }
}

我在控制器操作中添加以下示例数据 -

    public ActionResult Index()
    {
        QuestionSet q = new QuestionSet();
        q.Questions = new List<RegistrationQuestion>();
        q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi1?" });
        q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi2?" });
        q.Questions.Add(new RegistrationQuestion() { QuestionText = "hi3?" });
        return View(q);
    }

然后在您看来,您可以按照以下方式进行迭代 -

@for (int i = 0; i < Model.Questions.Count; i++)
{
    @Html.LabelFor(model => model.Questions[i].QuestionText, Model.Questions[i].QuestionText)
    @Html.EditorFor(model => model.Questions[i].QuestionText)
    <br/>
}

输出 -

enter image description here

答案 1 :(得分:0)

我通过为子模型创建局部视图然后根据需要动态插入(使用JavaScript / jQuery)来解决这个问题。