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