6

我正在尝试编写一个 foreach 循环来查找每个不同的类别类型,然后列出具有该类别分配的每个标题。

例如:

@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.)我需要它只显示每个类别一次,而不是列出每个项目实例的类别。

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

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

4

2 回答 2

3

如果我理解正确,那么它应该像

@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> 
  } 
} 
于 2012-07-03T18:44:12.757 回答
2

It looks like you need to group your enumeration by ProgramType in your controller. This will keep the view nice 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 view is much simpler. (After you fix 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 is slightly changed:

@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>
}
于 2012-07-03T19:03:21.260 回答