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";
@foreach (var group in Model)
<table class="table">
@foreach (var i in group)
<td>@Html.DisplayFor(modelItem => i.ResourceTitle)</td>
<td>@Html.DisplayFor(modelItem => i.ResourceDescription)</td>
<td>@Html.DisplayFor(modelItem => i.ResourceURL)</td>

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s