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.
![Table]()
Create table query
- CREATE TABLE [dbo].[Categories](
- [CategoryId] [int] primary key identity(1,1),
- [CategoryName] [varchar](40),
- [ParentCategoryId] [int],
- [Remarks] [nvarchar](max),
- )
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.
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.
- #region Declaration
- SqlConnection con;
- DataTable dt;
- #endregion
-
- #region Constructor
- public SqlAccess()
- {
- con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConStr"]);
- }
- #endregion
-
- #region KeyMethods
- public DataTable GetDataTableFromDb(string query)
- {
- SqlDataAdapter Adpt = new SqlDataAdapter(query, con);
- dt = new DataTable();
- try
- {
- Adpt.Fill(dt);
- }
- catch (SqlException ex)
- {
- dt = null;
- if (con.State == ConnectionState.Open)
- con.Close();
- }
- finally
- {
- if (con != null)
- if (con.State == ConnectionState.Open) con.Close();
- Adpt.Dispose();
- }
- return dt;
- }
- #endregion
Step 6
Add another class named HomeBAL in BusinessLayer. This class contains a method that passes query to SqlAccess and returns the DataTable.
- public DataTable GetAllCategories()
- {
- return new SqlAccess().GetDataTableFromDb("SELECT CategoryId, CategoryName, ParentCategoryId FROM Categories");
- }
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.