Displaying Results by Group in MVC

I wanted to display a list of records grouped by category. There were numerous ways that people were doing it online, many of which were overly difficult and/or did not work. Ultimately it simply comes down to a simple Linq statement in the controller with the appropriate @model statement on the view.

The following are the Category and Resource models created to map to their respective database tables.

public partial class Category{
     public int CategoryID { get; set; }
     public string CategoryName { get; set; }
     public virtual ICollection<Resource> Resources { get; set; }
}

public partial class Resource{
     public int ResourceID { get; set; }
     public string ResourceTitle { get; set; }
     public string ResourceDescription { get; set; }
     public string ResourceURL { get; set; }
     public string ResourceFilename { get; set; }
     public bool IsCentriqCreatedResource { get; set; }
     public bool IsVideoResource { get; set; }
     public int CategoryID { get; set; }
     public Nullable<System.DateTime> PostDate { get; set; }
     public virtual Category Category { get; set; }
}

In the controller we simply retrieve the results from our database and then use Linq to group the records by a specific column.

var resources = db.Resources.ToList();

var groupResources = from r in resources
group r by r.Category.CategoryName into g
orderby g.Key
select g;

return View(groupResources.ToList());

We then have a strongly typed model of type @model IEnumerable<IGrouping<>> and then loop through the content with nested foreach statements.

@model IEnumerable<IGrouping<string, Resource>>
@{
     ViewBag.Title = "Resources";
}
<h2>Resources</h2>
@foreach (var group in Model){
     <h3>@group.Key</h3>
     <table class="table">
          @foreach (var i in group){
               <tr>
                    <td>@Html.DisplayFor(modelItem => i.ResourceTitle)</td>
                    <td>@Html.DisplayFor(modelItem => i.ResourceDescription)</td>
                    <td>@Html.DisplayFor(modelItem => i.ResourceURL)</td>
               </tr>
          }
     </table>
}

This will display all of the resources with a header of the Category followed by a list of the resources under that category.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *