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

Using Treeview in ASP.Net MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
12 Comment(s)
 40092  View(s)
Rate this:

Using Treeview in ASP.Net MVC

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.

 


Question

By Anh Lun on   3 years ago
Great example. Newbie question. Can the tree view be put into a frame and have the children node clickable? Let me explain. Is it possible for me to put the tree view into a frame on the left of the window and when the user click on "Entity Relationship diagram". The right frame would show a picture or something? Same goes when user click on "Entity & Entity sets"?

Appreciated.
Thanks.

Question

By Rohit Kesharwani on   3 years ago
yes. you can do this by creating click event of children node by using javascript or jquery.

thanks.

Need some help

By Thekla Petro on   3 years ago
Hi Rohit,

Many thanks for this example. It works perfectly if Layout = null;
What should we do if the Layout is not null?

I would appreciate your help.

Thank you,
Thekla

Files not found

By Jason J on   2 years ago

where are these three files :treeview.css, jquery-1.7.1.min.js and jquery.treeview.js

Thanks

Jason


Add dynamicaly a menu and folder

By hama abdoul on   2 years ago
hi Rohit 
i wanna know if it possible for the user by using his interface to add a Chapter topic and subtopic

thanks 

Add dynamicaly a menu and folder.

By Rohit Kesharwani on   2 years ago
Could you explain your question in more detail form.
From your above explain I understand that you want to add a new Chapter Topic and its SubTopic in IList<Model> chapters.

Is it right?
If yes then answer is "In that case you need to creating an object type of List<Model>  instead of  IList<Model>", then you can add a Chapter topic and subtopic.

jstree view in mvc4 using database

By Prabha Chilthadka on   2 years ago
hi,
 you have hard coded the data. i want to get data from existing table.

In database i have two tables called customer and Account. Customer can hold more than one accounts.
ex:X
->001
->002
Y
->003
->004

Where I can find a files?

By Alex Colt on   one year ago
Thank you for your solution. It is were helpful for me...but it seams that without correct file your code does not work. ("~/Content/jquery.treeview.css", "~/Scripts/jquery-1.7.1.min.js", ~/Scripts/jquery.treeview.js").

Can you please send me a file or destination where I can downloaded it? 
I try find this file by name, but with that solution does not working. 

Thank you, 

Alex.

Please post me the js and css files and Images

By guru murthy on   one year ago
all are working, only the css are not loading properly.

gurumurthyjv@gmail.com

Populating Selected node

By swarna Konda on   4 months ago

Hi.


Thank you for providing sample on treeview.

I would like to expand the node based on id value. how can I do it?


Thank you in advance!


Regards,

Swarna


Nice article

By Aleksandra Nikolova on   3 months ago
Nice article, I use shieldui treeview control - it`s satisfies all my needs
https://demos.shieldui.com/mvc/treeview/basic-usage

Treeview, GenealogyTree

By Anthony Whalen on   2 months ago
Hi Chris,

I love your article, I have a couple of questions to ask,
one is I have 3 main tables.

One table is Individuals, the second table is Roles, and the table is Relationships. Now the way I have the tables setup is the Individual has relationship with the Relationships table, and the Roles table has relationship build with the Relationships table. Now all tables are created in code first, and they all work. The problem I am having and trying to figure out is building a genealogy tree. I believe the Treeview  will solve that.

Now the main table is that all the information is in is the Relationships table, and the way it works I call up two individuals from the individual table and with first and last names of each individual. Now I do the same for the Roles, which is basically how they are related. So that means my main table is the Relationships table, like Father  and Daughter, but as we all know when I call up let say the Roles from the Relationships table I am calling up a integer and that means a integer will be shown, the other thing I am trying to figure out how to setup relationship layout from the database since all the information is in the relationships table and the software is completely data driven from the back end.

The first question is since I am using a Relationship base on the tables which call up a integer instead of a name how to I change that in model, because correct me if I am wrong the model controls the tree. Which I can not call the Last Name column directly from the Individuals table or call up a role name directly from the Roles table, because I have the Id store in the Relationships table. The model in the way the treeview works as it will only call up one table at a time.

The next question is how do I make sure that I have lets say a mother and father with  2 daughters show up in the proper tree layout and so on.

So is there a solution to make this work in a tree view so it looks like a genealogy tree, all the tables are working great other than I am have a problem creating the hierarchical layout I want from the tables. Do know have solution to this problem, it would be greatly appreciated. I look forward to hearing from you soon.

Thanks

A


 

Don't want to miss updates? Please click the below button!

Follow MindStick