articles

Home / DeveloperSection / Articles / Using Treeview in ASP.Net MVC

Using Treeview in ASP.Net MVC

Chris Anderson 66917 21-Jan-2013

In this article, I am explaining  how to create a structure like treeview in asp.net mvc by using razor view engine . I am also using entity framework code first model.

  •   Open Visual Studio 2010
  •   Create a new ASP.Net MVC 3 or 4 web application and named it as    TreeViewMVC for this application.
  •  Choose Razor as the View engine and click OK
  •  Add a Controller in your project and give name as HomeController.
  • Create a model class in the Model folder as shown below:

Model class Chapter, Topic and SubTopic. Each class represents a table in the database and each instance represents a row in the database.

    public class Chapter
    {
        public int ChapterID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Topic> Topics { get; set; }
    }
    public class Topic
    {
        public int TopicID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<SubTopic> SubTopics { get; set; }
        public int ChapterID { get; set; }
        public virtual Chapter Chapter { get; set; }
    }
    public class SubTopic
    {
        public int SubTopicID { get; set; }
        public string Name { get; set; }
        public int TopicID { get; set; }
        public virtual Topic Topic { get; set; }

    }

 

Inherit DbContext in ChapterDbContext to create a table in the database and initialize model with some default data in the database.

    public class ChapterDbContext : DbContext
    {
        public DbSet<Chapter> Chapters { get; set; }
        public DbSet<Topic> Topics { get; set; }
        public DbSet<SubTopic> SubTopics { get; set; }
    }
    public class ModelInitializer : DropCreateDatabaseIfModelChanges<ChapterDbContext>
    {
        protected override void Seed(ChapterDbContext context)
        {
            var chapters = new List<Chapter>
            {
                new Chapter
                {
                    Name = "Entity Relationship Model"
                },
                new Chapter
                {
                    Name ="Relational Model"
                },
                new Chapter
                {
                    Name = "Normalization"
                }
            };
            var topics = new List<Topic>
            {
                new Topic
                {
                    Name = "Entity & Entity sets",                     Chapter = chapters.Single(m => m.Name == "Entity Relationship Model")
                },
                new Topic
                {
                    Name = "Mapping Constraints, Candidate & Primary key",
                    Chapter = chapters.Single(m => m.Name == "Entity Relationship Model")
                },
                new Topic
                {
                    Name = "Entity Relationship diagram",
                    Chapter = chapters.Single(m => m.Name == "Entity Relationship Model")
                },
                new Topic
                {
                    Name = "Integrity Constraints",
                    Chapter = chapters.Single(m => m.Name == "Relational Model")
                },
                new Topic
                {
                    Name = "Relational Algebra",
                    Chapter = chapters.Single(m => m.Name == "Relational Model")
                },
                new Topic
                {
                    Name = "Modifying the database",
                    Chapter = chapters.Single(m => m.Name == "Relational Model")
                },
                new Topic
                {
                    Name = "Introduction to functional dependence",
                    Chapter = chapters.Single(m => m.Name == "Normalization")
                },
                new Topic
                {
                    Name = "Normalization-1NF,2NF,3NF,BCNF,4NF,5NF",
                    Chapter = chapters.Single(m => m.Name == "Normalization")
                }
            };
            var subtopics = new List<SubTopic>
            {
                new SubTopic
                {
                    Name = "Entities",
                    Topic = topics.Single(m => m.Name == "Entity Relationship diagram")
                },
                new SubTopic
                {
                    Name = "Selection, Projection",
                    Topic = topics.Single(m => m.Name == "Relational Algebra")
                },
                new SubTopic
                {
                    Name = "Minimal Functional Dependencies",
                    Topic = topics.Single(m => m.Name == "Introduction to functional dependence")                 },
                new SubTopic
                {
                    Name = "Equivalent Functional Dependencies",
                    Topic = topics.Single(m => m.Name == "Introduction to functional dependence")
                }
            };
            chapters.ForEach(m => context.Chapters.Add(m));
            topics.ForEach(m => context.Topics.Add(m));
            subtopics.ForEach(m => context.SubTopics.Add(m));
        }
    }

 Add a Model class which represents a treeview structure in a view.

   public class Model
    {
        public Model()
        {
            this.List = new List<Model>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public IList<Model> List { get; private set; }
        public bool IsChild
        {
            get
            {
                return this.List.Count == 0;
            }
        }
    } 

 Add a connection string in the web.config file under the configuration tag:

  <connectionStrings>

    <add name="ChapterDbContext"connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=ChapterDb;Integrated Security=true;MultipleActiveResultSets=true;"providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

Modify the Global.asax file as shown below:

 protected void Application_Start()
        {
            Database.SetInitializer(new ModelInitializer());
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
 

Create a HomeController and add the following action methods. In this Index view return a list of chapter, topic and its subtopic after adding its data in single Model class.

   public class HomeController : Controller
    {         //create dbcontext object
        ChapterDbContext db = new ChapterDbContext();
        public ActionResult Index()
        {
            //get list to pass to data in view
            IList<Model> chapters = ChapterList();
            return View(chapters);
        }
        public IList<Model> ChapterList()
        {
            IList<Model> chapters = new List<Model>();
            foreach (var chapter in db.Chapters)
            {
                var chap = new Model
                {
                    Id = chapter.ChapterID,
                    Name = chapter.Name,
                    Type = "chapter"
                };
                foreach (var topic in chapter.Topics)
                {
                    var top = new Model
                    {
                        Id = topic.TopicID,
                        Name = topic.Name,
                        Type = "topic"
                    };
                    foreach (var subtopic in topic.SubTopics)
                    {
                        var subtop = new Model
                        {
                            Id = subtopic.SubTopicID,
                            Name = subtopic.Name,
                            Type = "subtopic"
                        };
                        top.List.Add(subtop);
                    }
                    chap.List.Add(top);
                }
                chapters.Add(chap);
            }
            return chapters;
        }
    } 

 

Add an Index View and modify this view as given below. Also includes three files in the given location ("~/Content/jquery.treeview.css", "~/Scripts/jquery-1.7.1.min.js", ~/Scripts/jquery.treeview.js").

@model IEnumerable<TreeViewMVC.Models.Model>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="@Url.Content("~/Content/jquery.treeview.css")" rel="stylesheet" type="text/css" />     <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>     <script src="@Url.Content("~/Scripts/jquery.treeview.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#chapterFolders').treeview({ collapsed: true });
        });
    </script>
</head>
<body>
    <div>
        @helper TreeView(IEnumerable<TreeViewMVC.Models.Model> items)
            {
                foreach (var item in items)
                {
            <li>
                @if (item.IsChild)
                {
                    <span class="leaf @item.Type" id="@item.Id">@item.Name</span>
                }
                else
                {
                    <span class="folder">@item.Name</span>
                    <ul>
                        @TreeView(item.List)
                    </ul>
                }
            </li>
                }
        }
        <h1>TreeView in ASP.Net MVC</h1>
        <ul id="chapterFolders" class="filetree treeview-famfamfam">
            @TreeView(Model)
        </ul>
    </div>
</body>
</html>


Save and Run your application, the output will something look like below. By default treeview nodes is in collapsed format.

Using Treeview in ASP.Net MVC

You can expand and view the child nodes as shown below:

Using Treeview in ASP.Net MVC

Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.

 


Updated 07-Sep-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By