我有一个foreach循环,它根据模型中的项目数构建超链接。它工作正常,除了说:ProgramId = @item.ProgramIds.First()
只返回每个ProgramType的第一个程序ID。让它循环遍历所有程序ID的语法是什么,而不仅仅是第一个?
@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; }
}
控制器操作:
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);
}
答案 0 :(得分:3)
item
指的是外循环的值。看起来你想要使用内循环中的值:
@foreach (var ProgramTitles in item.ProgramTitles)
{
foreach(var programId in item.ProgramIds)
{
<li>
@Html.ActionLink(ProgramTitles, "Results", "SurveyResponse", new { ProgramId = programId }, null)
</li>
}
}
提供viewModel之后,看起来你有ProgramTitles和ProgramIds作为两个断开连接的数组。也许,你所拥有的是ProgramTitle的数组索引n处的项目在ProgramIds数组的第n项中具有相应的条目。 viewModel可以改进,但这是我的解决方案:
@for (var index = 0; index < item.ProgramTitles.Count; index++)
{
<li>
@Html.ActionLink(ProgramTitles[index], "Results", "SurveyResponse", new { ProgramId = item.ProgramIds[index]}, null)
</li>
}
答案 1 :(得分:1)
我对你的模型和查询有点困惑。据我所知,程序和类型之间应该存在关系,而不是。
所以,我强烈建议您查看您的viewmodel及其查询。
但是,看看这是否有帮助:
@foreach (var currentProgramTypeViewModel in Model)
{
foreach(string currentProgramType in currentProgramTypeViewModel.ProgramTypes)
{
<h2>@currentProgramType</h2>
<ul>
@for (int mProgramIndex = 0; mProgramIndex < currentProgramTypeViewModel.ProgramIds.Count(); mProgramIndex++)
{
var programTitle = currentProgramTypeViewModel.ProgramTitles.ToList<string>()[mProgramIndex];
var programId = currentProgramTypeViewModel.ProgramIds.ToList<int>()[mProgramIndex];
<li>
@Html.ActionLink(programTitle, "Results", "SurveyResponse", new { ProgramId = programId }, null)
</li>
}
</ul>
}
}