Create Dynamic Tree View From Database In ASP.NET MVC 5 C#

In this article, we will create a dynamic tree view menu fetched from the database, using ASP.NET MVC 5, C#, Razor and SQL Server 2014 (using Visual Studio 2013). This article will guide you on how to display parent child tree view dynamically from the database. This is the best, easiest, and fastest way to make tree view. Let's try to populate it.

Step 1

Create a table and insert the records, as per your requirement. The table structure is given below.

Create table query

  1. CREATE TABLE [dbo].[Categories](  
  2.     [CategoryId] [intprimary key identity(1,1),  
  3.     [CategoryName] [varchar](40),  
  4.     [ParentCategoryId] [int],  
  5.     [Remarks] [nvarchar](max),  
  6. )  

Step 2

I have attached sample SQL query file named “categoryDb.sql” to create table and insert the records. Just run the query to make database and insert the records. You can insert records manually also.

Step 3

Create a new project and take Empty ASP.NET MVC Application. Here, I have used MVC 5 project.


Step 4

Add new Class Library Project. The solution is named Business Layer which contains an actual logic and an interaction with the database.


Step 5

Add new class named SqlAccess in BusinessLayer project. The class has a constructor to initialize SqlConnection and a method, which will take query in the string format and return rows in DataTable.

  1. #region Declaration  
  2. SqlConnection con;  
  3. DataTable dt;  
  4. #endregion  
  6. #region Constructor  
  7. public SqlAccess()  
  8. {  
  9.     con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConStr"]);  
  10. }  
  11. #endregion  
  13. #region KeyMethods  
  14. public DataTable GetDataTableFromDb(string query)  
  15. {  
  16.     SqlDataAdapter Adpt = new SqlDataAdapter(query, con);  
  17.     dt = new DataTable();  
  18.     try  
  19.     {  
  20.         Adpt.Fill(dt);  
  21.     }  
  22.     catch (SqlException ex)  
  23.     {  
  24.         dt = null;  
  25.         if (con.State == ConnectionState.Open)  
  26.             con.Close();  
  27.     }  
  28.     finally  
  29.     {  
  30.         if (con != null)  
  31.             if (con.State == ConnectionState.Open) con.Close();  
  32.         Adpt.Dispose();  
  33.     }  
  34.     return dt;  
  35. }  
  36. #endregion  

Step 6

Add another class named HomeBAL in BusinessLayer. This class contains a method that passes query to SqlAccess and returns the DataTable. 

  1. public DataTable GetAllCategories()  
  2. {  
  3.     return new SqlAccess().GetDataTableFromDb("SELECT CategoryId, CategoryName, ParentCategoryId FROM Categories");  
  4. }  

Step 7

Now, we need to access BusinessLayer members from our PresentationLayer (MVC Project). So, give the referenc of BusinessLayer to PresentationLayer.

Make sure that the BusinessLayer is referenced inside "References" of PresentationLayer.