Foreach inside of Foreach Razor

asp.net-mvc-3 c# entity-framework linq

Question

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.

For example:

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

Survey Response Model:

  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; }

}

I am running into 2 issues.

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

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.

1
6
7/3/2012 6:54:06 PM

Popular Answer

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> 
  } 
} 
3
11/3/2013 3:47:04 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow