Efficiently Displaying Hierarchical Data With The jQuery Accordion In Razor Web Pages

5 (8 votes)

A frequent requirement is to display data hierarchically, such as products by category. This article shows how to use LINQ to Objects and the jQuery Accordion to display the result of a database query in such a fashion within Razor Web Pages.

One of the problems that people get into when attempting to present hierarchical data on a web page is to fall into the trap if executing multiple database queries to obtain data. If they want to display a list of products by category, they first obtain all of the categories, and then iterate the categories and retrieve a list of products for each category. The code might look something like this:

@foreach(var category in db.Query("SELECT * FROM Categories")){
    foreach(var product in db.Query("SELECT * FROM Products WHERE CategoryId = @0", category.CategoryId)){

This is known as the n + 1 select problem, when 1 select query is executed to get the categories, then n further select queries are executed to get the products for each category. Generally, developers are encouraged to minimise the number of times their application makes calls to a database as this can be a common cause of performance issues. Ideally, you should get your data in one shot and then shape it appropriately. A one shot retrieval of data might result in a structure that looks like this:

Ideally, that should be shaped, so that each category's products are grouped together:

LINQ offers a GroupBy method that does just that - it groups elements of a sequence together based on a specified key. The sequence is the output from the database query, and the key around which items are grouped is the name of the category. The code looks like this:

    var db = Database.Open("Northwind");
    var sql = @"SELECT CategoryName, ProductId, ProductName FROM Categories 
                INNER JOIN Products ON Products.CategoryId = Categories.CategoryId 
                ORDER BY Categories.CategoryId";
    var categories = db.Query(sql).GroupBy(p => p.CategoryName);

Here's how that looks to the Visual Studio debugger:


Data is grouped around the 8 categories in the Northwind database. Getting this on the web page is a matter of two loops - one that iterates the groups, and another inner loop that iterates the content of the group:

@foreach (var category in categories) {
    @foreach (var product in category.OrderBy(p => p.ProductName)) {

The result is exactly as desired:

However, it is a long list, and might benefit from some UI enhancements like the jQuery accordion. The accordion hides all but one section of structured content until the user is ready to see it. It is available as part of the UI download, and is very easy to deploy to the page. Each section of data needs a header-content pair of elements. The example above has that; the category name appears in an h3 element and the list of products appear in a div. It needs a little modification to work with the accordion - a container and some links:

<div id="accordion">
    @foreach (var category in categories) {
        <h3><a href="#">@category.Key</a></h3>
        @foreach (var product in category.OrderBy(p => p.ProductName)) {

You can download the accordion and associated styles or link to one of the CDN hosters, and then specify one command to apply the accordion effect to the div labelled with the id of accordion and its contents:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
        $('#accordion').accordion({ autoHeight: false });

And finally here's how the result looks:

This purpose of this article was to illustrate how to use the LINQ GroupBy operator to prepare data in such a way that displaying it on a Razor Web Page hierarchically is simple and efficient. Finally, the jQuery Accordion was used to apply some user friendly features to the resulting data.

A GitHub repo is available containing the code as a sample web site


Date Posted:
Last Updated:
Posted by:
Total Views to date: 22651


- Keef

Excellent and easy to understand as usual.

- Zeljko

Great article, the only thing I would change in your code is to move the query to the controller and send the prepared object to the view via a customized viewmodel.

- Mike


In MVC, your suggestion is exactly how it should be done. There are, however, no controllers in Razor Web Pages.

- Zeljko

You're absolutely right. I should have paid more attention to the title of your blog post. Somehow I was under the impression it was an MVC post.

- Maran

Hello Mike,
I can't see the images...

- Mike


Check your firewall rules. They are hosted at livestore.com.

Recent Comments

raphael 27/11/2015 13:59
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
i fixed it. i'm not sure *what* it is that VS does, but you get the same result if you do a "npm on...

Raphael 27/11/2015 13:02
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
There seems to be a major issue with the dependency manager in VS2015. I haven't yet figured out but...

Joaquín Bresan 26/11/2015 17:58
In response to Getting the identity of the most recently added record
Great contribution friend. Thank you so much for sharing....

sumalatha 24/11/2015 22:09
In response to ASP.NET 5 Middleware, Or Where Has My HttpModule Gone?
Great article. I have gone through hundreds of articles, finally this gives the comprehensive of...

Rajasekar 24/11/2015 12:27
In response to Import Data From Excel to Access with ASP.NET
While use this code i'm facing on error: "Unrecognized Database format C:\mydabase.accdb" can any...

Parmod 24/11/2015 07:28
In response to ASP.NET 5 Project Basics
For a new learner (Fresher) in ASP.NET there is a issue Fresher have to learn two types of , old...

Robert 22/11/2015 21:35
In response to ASP.NET 5 By Numbers
I have to agree fully with Paul, this does sound like an entire mis-mash of technologies. Sort of in...

Christian 21/11/2015 15:46
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model
Many thanks Mike to introduce me in the EF6 Code First way of thinking. Exactly what I need for my...

ax plains 20/11/2015 16:29
In response to Examining the Details and Delete Methods
Hello, really great tutorial for a beginner like me! Is it possible to have an explanation on how a...

Abdul Latif 20/11/2015 14:42
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Could anyone please help me, I am getting : "OfficeOpenXml.ExcelPackage" does not contain a for...