我有以下课程:
public class CourseSection
{
[Key]
public int CourseSectionID { get; set; }
public int CourseID { get; set; }
public string Title { get; set; }
public virtual ICollection<SectionContent> SectionContents { get; set; }
}
子类SectionContent如下所示:
public class SectionContent
{
[Key, Column(Order = 0)]
public int CourseSectionID { get; set; }
[ForeignKey("CourseSectionID")]
public virtual CourseSection CourseSection { get; set; }
[Key, Column(Order = 1)]
public int ContentID { get; set; }
[ForeignKey("ContentID ")]
public virtual Content Content { get; set; }
public int ContentOrder { get; set; }
}
我希望能够根据ContentOrder字段对sectioncontent列表进行排序,我在sectioncontent表中有以下数据:
CourseSectionID ContentID ContentOrder
1 212 1
1 208 2
1 214 3
1 210 4
但是在视图中显示此内容时,我无法根据ContentOrder属性对部分内容进行排序。它基于ContentID显示,因此显示为208,210,212,214。如何根据此属性订购SectionContents?这是我的剃刀视图代码:
foreach (var sectionItem in Model.CourseSections)
{
<li>
<h5 class="accordion-title">@sectionItem.Title<span class="accordion-icon"></span></h5>
<div class="accordion-content">
<ul>
@foreach (var subSectionItem in sectionItem.SectionContents)
{
<li><a href="#" id="menuItem @subSectionItem.ContentID @sectionItem.CourseSectionID" onclick="SubItemMenu(id)">@subSectionItem.Content.Name</a></li>
}
</ul>
</div>
</li>
}
答案 0 :(得分:2)
只需在OrderBy()
...
foreach
语句即可
foreach (var sectionItem in Model.CourseSections)
{
<li>
<h5 class="accordion-title">@sectionItem.Title<span class="accordion-icon"></span></h5>
<div class="accordion-content">
<ul>
@foreach (var subSectionItem in sectionItem.SectionContents.OrderBy(sc => sc.ContentOrder))
{
<li><a href="#" id="menuItem @subSectionItem.ContentID @sectionItem.CourseSectionID" onclick="SubItemMenu(id)">@subSectionItem.Content.Name</a></li>
}
</ul>
</div>
</li>
}
或者,您可以在首先获取数据时执行OrderBy()
,然后假设视图中的所有内容都是正确的 - 选择权归您所有。
答案 1 :(得分:1)
您正在寻找OrderBy扩展方法。
@foreach (var subSectionItem in sectionItem.SectionContents.OrderBy(item => item.ContentOrder))
{
<li><a href="#" id="menuItem @subSectionItem.ContentID @sectionItem.CourseSectionID" onclick="SubItemMenu(id)">@subSectionItem.Content.Name</a></li>
}
答案 2 :(得分:1)
我想你有一些返回CourseSection模型的服务方法。在该方法中,设置已排序的模型属性:
var myCourseModel = buildMyCourseSection();
myCourseModel.SectionContents = (from sc in myCourseModel.SectionContents
order by sc.ContentOrder
select sc).ToArray();