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

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")){
    <h3>@category.CategoryName</h3>
    foreach(var product in db.Query("SELECT * FROM Products WHERE CategoryId = @0", category.CategoryId)){
        <div>@product.ProductName</div>
    }
}

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) {
    <h3>@category.Key</h3>
    <div>
    @foreach (var product in category.OrderBy(p => p.ProductName)) {
        <div>@product.ProductName</div>
    }
    </div>
}

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>
        <div>
        @foreach (var product in category.OrderBy(p => p.ProductName)) {
            <div>@product.ProductName</div>
        }
        </div>
    }
</div>

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">
    $(function(){
        $('#accordion').accordion({ autoHeight: false });
    });
</script>

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: 21842

6 Comments

- 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

@Zeljko

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

@Maran,

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

Recent Comments

sandeep 8/28/2015 7:03 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
very good article, i like it........keep writing such quality article in future. thx Mike....

Hassan, MVC Learner 8/28/2015 6:37 AM
In response to Get The Drop On ASP.NET MVC DropDownLists
Great Help, simple, great and patiently explained article !...

Anvesh 8/28/2015 12:39 AM
In response to ASP.NET MVC DropDownLists - Multiple Selection and Enum Support
what if we are taking postback values from FormCollections instead of an array int[] category. How...

Ben 8/27/2015 10:50 PM
In response to Simple File Download Protection with ASP.NET
Is it possible to setup your project to publish files to outside of your root directory? I would to...

Fred 8/26/2015 12:50 AM
In response to WebMatrix Opens Wrong Version Of Visual Studio
I enjoyed many of your tutorials but the problem is none of the tutorials are combined like most be....

Muhammad Ashikuzzaman 8/25/2015 2:48 PM
In response to Managing Checkboxes And Radios In ASP.NET Razor Web Pages
That's a very good tips for razor...

Sergey 8/25/2015 8:32 AM
In response to More Flexible Routing For ASP.NET Web Pages
Hi. How I can set up my site to get urldata from link for default page? site.com/default/1-...

Tony Gray 8/25/2015 6:27 AM
In response to Adding Validation
Hi Mike, Really helpful article and series. Thanks. Small typo in 4th paragraph you have so...

amanda n 8/25/2015 12:38 AM
In response to Solving the Operation Must Use An Updateable Query error
Thank you very much. I'm a uni student and while solving coding problems is usually enjoyable and me...

salman 8/23/2015 9:25 AM
In response to How To Send Email In ASP.NET MVC
thanks ......