Solutions For Menu In ASP.NET Core

Introduction

In this article, you will learn some solutions to deal with the menus in ASP.NET Core. You also can find something common that can be used in other frameworks or other programming languages too.

Background

Menus are required in most of our systems, such as electronic mails and manager systems .etc. Most of the time, we may store the menus in our databases, so that we can manage them easily. And, this article is based on this scenario.

I will use the menu structure of an open source project named AdminLTE to demonstrate my solutions.

Let's take a look at the menu structure at first.

  1. <ul class="sidebar-menu">  
  2.     <li class="treeview">  
  3.       <a href="#">  
  4.         <i class="fa fa-share"></i> <span>Multilevel</span>  
  5.         <span class="pull-right-container">  
  6.           <i class="fa fa-angle-left pull-right"></i>  
  7.         </span>  
  8.       </a>  
  9.       <ul class="treeview-menu">          
  10.         <li>  
  11.           <a href="#"><i class="fa fa-circle-o"></i> Level One  
  12.             <span class="pull-right-container">  
  13.               <i class="fa fa-angle-left pull-right"></i>  
  14.             </span>  
  15.           </a>  
  16.           <ul class="treeview-menu">            
  17.             <li>  
  18.               <a href="#"><i class="fa fa-circle-o"></i> Level Two  
  19.                 <span class="pull-right-container">  
  20.                   <i class="fa fa-angle-left pull-right"></i>  
  21.                 </span>  
  22.               </a>  
  23.               <ul class="treeview-menu">  
  24.                 <li><a href="#"><i class="fa fa-circle-o"></i> Level Three</a></li>  
  25.               </ul>  
  26.             </li>              
  27.           </ul>  
  28.         </li>          
  29.       </ul>  
  30. </li>  
  31. </ul>  

 After looking the structure of the menu, we can design a table to store the infomation of the menus. Here is the sample table on my PostgreSQL.

  1. DROP TABLE IF EXISTS "public"."menu";CREATE TABLE "public"."menu" (  
  2.         "id" varchar(50) NOT NULL COLLATE "default",  
  3.         "parentid" varchar(50) COLLATE "default",  
  4.         "content" varchar(50) COLLATE "default",  
  5.         "iconclass" varchar(100) COLLATE "default",  
  6.         "href" varchar(200) COLLATE "default",  
  7.         "order" int8  
  8. )WITH (OIDS=FALSE);  
  9. ALTER TABLE "public"."menu" OWNER TO "postgres";  
  10. ALTER TABLE "public"."menu" ADD PRIMARY KEY ("id"NOT DEFERRABLE INITIALLY IMMEDIATE;  

 After creating the table, we also need some sample data to demonstrate.

  1. BEGIN;  
  2. INSERT INTO "public"."menu" VALUES ('E3A80BB6-B6BA-4F51-8EF2-123D6CD21E7F'null'first level 01''fa fa-book''/''1');  
  3. INSERT INTO "public"."menu" VALUES ('7034B962-C54C-4B2C-92D4-439C0320F04B''E3A80BB6-B6BA-4F51-8EF2-123D6CD21E7F''second level 01''fa fa-circle-o text-aqua''/''1');  
  4. INSERT INTO "public"."menu" VALUES ('F3400C61-D324-4078-A88D-5CD66E143216''E3A80BB6-B6BA-4F51-8EF2-123D6CD21E7F''second level 02''fa fa-circle-o text-aqua''/''2');  
  5. INSERT INTO "public"."menu" VALUES ('B819B800-484F-4947-A36E-9A5E34F8CCA9''7034B962-C54C-4B2C-92D4-439C0320F04B''third level 01''fa fa-circle-o''/''1');  
  6. INSERT INTO "public"."menu" VALUES ('1FC65DDB-94F2-4ADF-8891-C8E853362D59'null'first level 02''fa fa-book''/''0');  
  7. INSERT INTO "public"."menu" VALUES ('E8C67B83-D38C-4682-A39E-0CE5BDC16FA5''1FC65DDB-94F2-4ADF-8891-C8E853362D59''new menu''fa fa-circle-o''/''100');  
  8. COMMIT;  

So far, we have finished the previous job of our database. Here is the result of my sample data.

sample data
Now, we need to define some Entities, map the columns of our table, and define some functions to operate.

Entity definition first

  1. public class Menu  
  2. {  
  3.     public string ID { get; set; }  
  4.     public string ParentID { get; set; }  
  5.     public string Content { get; set; }  
  6.     public string IconClass { get; set; }  
  7.     public string Url { get; set; }  
  8.     public long Order { get; set; }  
  9. }  
  10. public class MenuViewModel  
  11. {  
  12.     public string ID { get; set; }  
  13.     public string Content { get; set; }  
  14.     public string IconClass { get; set; }  
  15.     public string Url { get; set; }  
  16.     public IList<MenuViewModel> Children {get;set;}  
  17. }  

Functions to opreate the menus,

  1. private IList<Menu> GetAllMenuItems()  
  2. {  
  3.     using (IDbConnection conn = new NpgsqlConnection(connStr))  
  4.     {  
  5.         try  
  6.         {  
  7.             conn.Open();  
  8.             var sql = @"SELECT * FROM public.menu;";  
  9.             return conn.Query<Menu>(sql).ToList();  
  10.         }  
  11.         catch (Exception ex)  
  12.         {  
  13.             return new List<Menu>();  
  14.         }  
  15.     }   
  16. }  
  17.   
  18. private IList<Menu> GetChildrenMenu(IList<Menu> menuList,string parentId=null)  
  19. {  
  20.     return menuList.Where(x => x.ParentID == parentId).OrderBy(x=>x.Order).ToList();  
  21. }  
  22. private Menu GetMenuItem(IList<Menu> menuList, string id)  
  23. {  
  24.     return menuList.FirstOrDefault(x => x.ID == id);  
  25. }  

Solutions are coming!

Solution #1 Building HTML string in Controller

In this solution, we will build an HTML string in our Controller which will return a string to the View, and we need to render this string through `Html.Raw()` or other ways.

Controller first

  1. [Route("string")]  
  2. public IActionResult RenderString()  
  3. {             
  4.     return View("String",GetMenuString());  
  5. }  
  6. private string GetMenuString()  
  7. {  
  8.     var menuItems = GetAllMenuItems();  
  9.   
  10.     var builder = new StringBuilder();  
  11.     builder.Append("<ul class=\"sidebar-menu\">");  
  12.     builder.Append(GetMenuLiString(menuItems, null));  
  13.     builder.Append("</ul>");  
  14.     return builder.ToString();                  
  15. }  
  16. private string GetMenuLiString(IList<Menu> menuList, string parentId)  
  17. {             
  18.     var children = GetChildrenMenu(menuList, parentId);  
  19.   
  20.     if(children.Count<=0)  
  21.     {  
  22.         return "";  
  23.     }  
  24.   
  25.     var builder = new StringBuilder();  
  26.   
  27.     foreach (var item in children)  
  28.     {  
  29.         var childStr = GetMenuLiString(menuList, item.ID);  
  30.         if(!string.IsNullOrWhiteSpace(childStr))  
  31.         {  
  32.             builder.Append("<li class=\"treeview\">");  
  33.             builder.Append("<a href=\"#\">");  
  34.             builder.AppendFormat("<i class=\"{0}\"></i> <span>{1}</span>",item.IconClass,item.Content);  
  35.             builder.Append("<span class=\"pull-right-container\">");  
  36.             builder.Append("<i class=\"fa fa-angle-left pull-right\"></i>");  
  37.             builder.Append("</span>");  
  38.             builder.Append("</a>");  
  39.             builder.Append("<ul class=\"treeview-menu\">");  
  40.             builder.Append(childStr);  
  41.             builder.Append("</ul>");  
  42.             builder.Append("</li>");  
  43.         }  
  44.         else  
  45.         {  
  46.             builder.Append("<li class=\"treeview\">");  
  47.             builder.AppendFormat("<a href=\"{0}\">",item.Href);  
  48.             builder.AppendFormat("<i class=\"{0}\"></i> <span>{1}</span>",item.IconClass,item.Content);                
  49.             builder.Append("</a>");  
  50.             builder.Append("</li>");  
  51.         }  
  52.     }  
  53.   
  54.     return builder.ToString();  
  55. }  

As you can see, we just build a string based on the menu structure. You also can use ViewBag or ViewData to finish the same job.

In the View, we only need one line code to render the menus.

  1. @Html.Raw(Model)  

Here is the result of running this code (All of the solutions have the same result).

solutions

Before following the solutions, we need to add a function to get the tree menus, mainly for recursion.

  1. private IList<MenuViewModel> GetMenu(IList<Menu> menuList, string parentId)  
  2. {  
  3.     var children = GetChildrenMenu(menuList, parentId);  
  4.   
  5.     if (!children.Any())  
  6.     {  
  7.         return new List<MenuViewModel>();  
  8.     }  
  9.   
  10.     var vmList = new List<MenuViewModel>();  
  11.     foreach (var item in children)  
  12.     {  
  13.         var menu = GetMenuItem(menuList, item.ID);  
  14.   
  15.         var vm = new MenuViewModel();  
  16.   
  17.         vm.ID = menu.ID;  
  18.         vm.Content = menu.Content;  
  19.         vm.IconClass = menu.IconClass;  
  20.         vm.Href = menu.Href;  
  21.         vm.Children = GetMenu(menuList, menu.ID);  
  22.   
  23.         vmList.Add(vm);  
  24.     }  
  25.   
  26.     return vmList;  
  27. }  

Solution #2 Tree Menu Entity + PartialView

In this solution, we will return a tree menu entity to the View, and render the View through this entity.

In the below code we are defining a partial View named _MenuPartial.cshtml , and its content.

  1. @model System.Collections.Generic.IEnumerable<Catcher.CoreDemo.Controllers.Learn01.MenuViewModel>  
  2.   
  3. @foreach (var menu in Model)  
  4. {  
  5.     if (menu.Children.Any())  
  6.     {  
  7.     <li class="treeview">  
  8.         <a href="#">  
  9.             <i class="@menu.IconClass"></i> <span>@menu.Content</span>  
  10.             <span class="pull-right-container">  
  11.                 <i class="fa fa-angle-left pull-right"></i>  
  12.             </span>  
  13.         </a>  
  14.         <ul class="treeview-menu">            
  15.             @Html.Partial("_MenuPartial",menu.Children)  
  16.         </ul>  
  17.     </li>  
  18.     }  
  19.     else  
  20.     {  
  21.         <li class="treeview">  
  22.             <a href="@menu.Href">  
  23.                 <i class="@menu.IconClass"></i> <span>@menu.Content</span>                          
  24.             </a>                   
  25.         </li>  
  26.     }  
  27. }  

Note - We need to include current partial View in the loop so that we can render all the nodes of menus, because we can not know how many nodes the menus have .

As you can see, we mainly deal with the LI tag in Partial View, so we need to add the UL tag when we use the partial View.

  1. <ul class="sidebar-menu">           
  2.    @Html.Partial("_MenuPartial",Model)  
  3. </ul>  

Turning to our Controller, we only need to return menu data to the View.

  1. [Route("model")]  
  2. public IActionResult Model()  
  3. {              
  4.     var menuItems = GetAllMenuItems();  
  5.     return View("Model",GetMenuData(menuItems,null));  
  6. }  

Solution #3 ViewComponent

ViewComponent is not a new feature in ASP.NET Core , but we can use this feture to finish many jobs. This solution is similar to the previous solution. Both of them return a Vie but with a minor difference that can be seen easily.

Defining a new ViewComponent named MenuViewComponent

  1. public class MenuViewComponent : ViewComponent  
  2. {  
  3.     public async Task<IViewComponentResult> InvokeAsync()  
  4.     {  
  5.         var menuItems = await GetAllMenuItems();  
  6.         return View(GetMenuData(menuItems, null));  
  7.     }  
  8. }  

Note - When we do not specify the name of the View, we should use the Default.cshtml as our View's name. And, we put this file in the path "your project/Views/Shared/Components/Menu". The content of this View is same as in  _MenuPartial.cshtml.

And how to use this component? - Just call Component.InvokeAsync to use !

Here is an example.

  1. <ul class="sidebar-menu">           
  2.    @await Component.InvokeAsync("Menu")  
  3. </ul>  

The above three solutions may be suitable for most of ASP.NET projects, such as WebForm, MVC. and Core. These solutions are mostly based on AJAX and JSON data so that most of the web projects can use.

Let's define a action to return the JSON data of the menus.

  1. [Route("getdata")]  
  2. public IActionResult GetData()  
  3. {  
  4.     return Json(GetMenuData());  
  5. }  

The above code uses the JsonResult to compile. Json.NET can also finish this job as well.

When calling this action in our View, we will get the JSON data.

  1. [  
  2.     {  
  3.         "id""E3A80BB6-B6BA-4F51-8EF2-123D6CD21E7F",  
  4.         "content""first level 01",  
  5.         "iconClass""fa fa-book",  
  6.         "href""/",  
  7.         "children": [  
  8.             {  
  9.                 "id""7034B962-C54C-4B2C-92D4-439C0320F04B",  
  10.                 "content""second level 01",  
  11.                 "iconClass""fa fa-circle-o text-aqua",  
  12.                 "href""/",  
  13.                 "children": [  
  14.                     {  
  15.                         "id""B819B800-484F-4947-A36E-9A5E34F8CCA9",  
  16.                         "content""third level 01",  
  17.                         "iconClass""fa fa-circle-o",  
  18.                         "href""/",  
  19.                         "children": []  
  20.                     }  
  21.                 ]  
  22.             }  
  23.         ]  
  24.     }  
  25. ]  

Solution #4 JSON Data + DOM manipulation

This solution is based on DOM manipulation. After getting the JSON data through AJAX, we will build a HTML string. At last, using append or appentTo to add DOM to element.

Defining a UL element in the View.

  1. <ul class="sidebar-menu" id="menu"></ul>  

 Using the JavaScript code to deal with DOM.

  1. $(function(){  
  2.     $.ajax({  
  3.         url:"/menu/getdata",  
  4.         dataType:"json",  
  5.         method:"get",  
  6.         success:function(data){              
  7.             $(getMenusByConcat(data)).appendTo("#menu");           
  8.         }  
  9.     });         
  10.   
  11.     function getMenusByConcat(data){  
  12.         var dom = '';  
  13.       
  14.         for(var i = 0;i<data.length;i++){  
  15.             dom+='<li class="treeview">';  
  16.   
  17.             if(data[i].children.length>0)  
  18.             {  
  19.                 dom+='<a href="#">';  
  20.                 dom+='<i class="' + data[i].iconClass +  '"></i> <span>'+ data[i].content +'</span>';  
  21.                 dom+='<span class="pull-right-container">';  
  22.                 dom+='<i class="fa fa-angle-left pull-right"></i>';  
  23.                 dom+='</span>';  
  24.                 dom+='</a>';  
  25.   
  26.                 dom+='<ul class="treeview-menu">';  
  27.                 dom+=getMenusByConcat(data[i].children);  
  28.                 dom+='</ul>';  
  29.             }  
  30.             else  
  31.             {  
  32.                 dom+='<a href="'+ data[i].href +'"><i class="' + data[i].iconClass +  '"></i> <span>'+ data[i].content +'</span></a>';   
  33.             }  
  34.   
  35.             dom+='</li>';  
  36.         }   
  37.           
  38.         return dom;  
  39.     }  
  40. });  

Solution #5 JSON Data + Template Engine

This solution uses a Template Engine (ArtTemplate) to reduce the opreation of DOM. We just define the template and tell it how to render the data.

Take a look at the View's code.

  1. <ul class="sidebar-menu" id="menu"></ul>  
  2. <script id="demo" type="text/html">    
  3.     {{each}}  
  4.     <li class="treeview">  
  5.         {{if $value.children.length>0}}  
  6.         <a href="#">  
  7.         <i class="{{$value.iconClass}}"></i> <span>{{$value.content}}</span>  
  8.         <span class="pull-right-container">  
  9.           <i class="fa fa-angle-left pull-right"></i>  
  10.         </span>  
  11.         </a>      
  12.         <ul class="treeview-menu">  
  13.              {{include 'demo' $value.children}}  
  14.         </ul>    
  15.       
  16.         {{else}}  
  17.         <a href="{{$value.href}}">  
  18.         <i class="{{$value.iconClass}}"></i> <span>{{$value.content}}</span>  
  19.         </a>      
  20.         {{/if}}  
  21.     </li>  
  22.     {{/each}}      
  23.  </script>  

There are two parts of the above code - 

The first part is to define an empty shell of the menu, while the second part is the template which will render the data.

The most important code of the template is the following code dealing with recursion.

  1. {{include 'demo' $value.children}}  

Note - When using ArtTemplate, we need to define a template using the script tag with a text/html type.

And the JavaScript code is shown below.

  1. $(function(){  
  2.     $.ajax({  
  3.         url:"/menu/getdata",  
  4.         dataType:"json",  
  5.         method:"get",  
  6.         success:function(data){  
  7.             getMenuByArtTemplate(data);  
  8.         }  
  9.     });      
  10.   
  11.     function getMenuByArtTemplate(data){  
  12.         $("#menu").empty();  
  13.         var html = template('demo', data);  
  14.         $("#menu").html(html);  
  15.     }  
  16. });  

 You can try the below Template Engines as well. Both of them help us to finish some complex DOM manipulation.

Solution #6 JSON Data + VueJS

This solution uses VueJS to render the View, which is similar to AngularJS and React.

For more infomation about VueJS, you can visit its official website : <http://vuejs.org/>

Because a vue component needs a root element, so we need to make a little change on the menu structure.

Here is the code of the View.

  1. <div id="menu">  
  2.     <item :model="treeData" class="sidebar-menu"></item>  
  3. </div>  
  4. <script type="text/x-template" id="item-template">  
  5. <ul>  
  6.     <li class="treeview" v-for="item in model">  
  7.         <a href="#" v-if="item.children.length>0">  
  8.         <i :class="item.iconClass"></i> <span>{{item.content}}</span>  
  9.         <span class="pull-right-container">  
  10.           <i class="fa fa-angle-left pull-right"></i>  
  11.         </span>  
  12.         </a>  
  13.         <item :model="item.children" class="treeview-menu" v-if="item.children.length>0">  
  14.         </item>  
  15.           
  16.         <a :href="item.href" v-if="item.children.length<=0">  
  17.           <i :class="item.iconClass"></i> <span>{{item.content}}</span>   
  18.         </a>      
  19. </li>  
  20. </ul>  
  21. </script>  

The tag item is a component defined in the JS code.

  1. Vue.component('item', {  
  2.   template: '#item-template',  
  3.   props: {  
  4.     model: Object  
  5.   }  
  6. })  
  7.   
  8. var demo = new Vue({  
  9.   el: '#menu',  
  10.   data: {  
  11.     treeData: null      
  12.   },  
  13.   methods:{  
  14.     getMenuData:function(){  
  15.       var vm = this;  
  16.       axios.get('/menu/getdata')  
  17.       .then(function(res){  
  18.         vm.treeData = res.data;  
  19.       });  
  20.     }  
  21.   },  
  22.   mounted:function(){  
  23.     this.getMenuData();  
  24.   }  
  25. })  

Note - I used a JavaScript library named Axios to send an HTTP request!

Summary

This article introduced Six regular solutions to deal with the menus. As for me, I will suggest that you not use the Solution #1 and Solution #4.

Here are the reasons:

  1. Need a lot of time to build a HTML string.
  2. More prone to make mistakes, such as escape character.
  3. If you have plenty of menus, it may not perform very well.

Solution #2 and Solution #3 may be the easier solutions for a .NET devoloper. Solution #5 and Solution #6 need a little more of JavaScript technologies.