Foreach剃须刀内的Foreach [英] Foreach inside of Foreach Razor

查看:72
本文介绍了Foreach剃须刀内的Foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个foreach循环,该循环将找到每种不同的类别类型,然后列出具有该类别分配的每个Title.

I am trying to write a foreach loop that will find each distinct category type, and then list each Title that has that category assignment.

例如:

@model IEnumerable<CMESurvey.Models.SurveyProgramModel>

@{
    ViewBag.Title = "Home";
}

@foreach (var item in Model) {
    <h2>@Html.DisplayFor(modelItem => item.ProgramType.ProgramType)</h2>
    foreach (var listing in Model)
    {
        <ul>
            <li>@Html.DisplayFor(modelItem => listing.ProgramTitle)</li>
        </ul>
    }
}

调查响应模型:

  public class SurveyProgramModel
{

    [Key]
    public int ProgramId { get; set; }

    public int ProgramYear { get; set; }

    public int ProgramStatusId { get; set; }

    public string ProgramTitle { get; set; }



public virtual SurveyProgramModel SurveyProgramModel { get; set; }

public virtual PersonModel PersonModel { get; set; }

}

我遇到了2个问题.

1.)我需要它仅显示每个类别一次,而不是列出每个项目实例的类别.

1.) I need it to only display each category once, rather than listing the category for each item instance.

2.)它显示所有ProgramTitle,而不仅仅是该循环的ProgramTitle.

2.) It is displaying all ProgramTitle, rather than just the the the ProgramTitle for that loop.

不确定我应该使用什么语法.

Not sure what the syntax I should be using is.

推荐答案

如果我正确理解,那应该是

If I understand correctly then it should be like

@foreach (var item in Model) { 
  <h2>@Html.DisplayFor(modelItem => item.ProgramType.ProgramType)</h2> 
  foreach (var listing in item.SurveyResponseModels) 
  { 
     <ul> 
       <li>@Html.DisplayFor(modelItem => listing.ProgramTitle)</li> 
     </ul> 
  } 
} 

这篇关于Foreach剃须刀内的Foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆