Foreach inside the razor Foreach

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

For instance:

@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 have 2 questions running.

1.) I need it to display only each category once, and not indicate a category for each instance of the element.

2.) It displays the entire ProgramTitle, not just the ProgramTitle for this loop.

Not sure which syntax I should use.

+6
source share
2 answers

If I understand correctly, 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
source

It looks like you need to group your enum using ProgramType in your controller. This will keep the view beautiful and clean.

 IEnumerable<CMESurvey.Models.SurveyProgramModel> models = Foo(); //however you got them... var grouped = models.GroupBy(s => s.ProgramType.ProgramType); return View(grouped); 

Then your opinion is much simpler. (After you correct the type of your model).

 @for(int i = 0; i < Model.Count; i++) { <h2>@Html.DisplayFor(model => model[i].Key)</h2> <ul> for(int j = 0; j < Model[i].Count; j++) { <li>@Html.DisplayFor(model => model[i][j].ProgramTitle)</li> } </ul> } 

Alternative:

Or you make a list of lists:

 var models = Foo(); var grouped = models.GroupBy(s => s.ProgramType.ProgramType) .Select(x => x.Select(y => y)) .ToList(); return View(grouped); 

Then your view will change slightly:

 @for(int i = 0; i < Model.Count; i++) { <h2>@Html.DisplayFor(model => model[i].First().ProgramType.ProgramType)</h2> <ul> for(int j = 0; j < Model[i].Count; j++) { <li>@Html.DisplayFor(model => model[i][j].ProgramTitle)</li> } </ul> } 
+2
source

Source: https://habr.com/ru/post/919613/


All Articles