I have a foreach loop that builds hyperlinks based on the number of items in the model. It’s working fine, except the part that says: ProgramId = @item.ProgramIds.First() is only returning the first program ID for each ProgramType. What is the syntax for letting it loop through all of the program ID’s rather than just the first?
@model IEnumerable<CMESurvey.ViewModels.ProgramTypeViewModel>
@{
ViewBag.Title = "Home";
}
@foreach (var item in Model)
{
<h2>@Html.DisplayFor(modelItem => item.ProgramTypes)</h2>
<ul>
@foreach (var ProgramTitles in item.ProgramTitles)
{
<li>
@Html.ActionLink(@ProgramTitles, "Results", "SurveyResponse", new { ProgramId = @item.ProgramIds.First() }, null)
</li>
}
</ul>
}
public class ProgramTypeViewModel
{
public int ProgramTypeIds { get; set; }
public IEnumerable<string> ProgramTitles { get; set; }
public IEnumerable<int> ProgramIds { get; set; }
public IEnumerable<string> ProgramTypes { get; set; }
}
Controller action:
public ViewResult Home()
{
var data = from SurveyProgramModel in surveyProgramRepository.Get()
group SurveyProgramModel by SurveyProgramModel.ProgramTypeId into programTypeGroup
select new ProgramTypeViewModel()
{
ProgramTypeIds = programTypeGroup.Key,
ProgramIds = programTypeGroup.Select(r => r.ProgramId),
ProgramTitles = programTypeGroup.Select(r => r.ProgramTitle),
ProgramTypes = programTypeGroup.Select(r => r.ProgramType.ProgramType).Distinct(),
};
return View(data);
}
I’m a little bit confused with your model and query. As far as I can understand, there should be a relationship between program and type, which there isn’t.
So, I’d strongly recommend you to review your viewmodel and its query.
However, see if this helps: