I have the following class:
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; }
}
And the child class SectionContent is as shown here:
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; }
}
I want to be able to sort the list of sectioncontent based on the ContentOrder field, I have the following data in my sectioncontent table:
CourseSectionID ContentID ContentOrder
1 212 1
1 208 2
1 214 3
1 210 4
But when displaying this in the view I have been unable to order the section contents based on the ContentOrder property. It is being displayed based on ContentID so it is showing as 208,210,212,214. How can I order the SectionContents based on this property? This is my razor view code:
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>
}
The OrderBy extension method is what you're looking for.
@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>
}