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.
You can expand and view the child nodes as shown below:
Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.
Rahul Kesharwani
19-May-2020thanks for sharing for a good example
gowri shankar
10-May-2018hi ,it is really a useful article. do u have any solution for doing crud operation in tree view control
Anthony Whalen
13-Sep-2016I 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
Aleksandra Nikolova
11-Aug-2016https://demos.shieldui.com/mvc/treeview/basic-usage
swarna Konda
15-Jul-2016Hi.
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
guru murthy
06-Dec-2015Alex Colt
15-Feb-2015Can you please send me a file or destination where I can downloaded it?
Prabha Chilthadka
01-Dec-2014Chris Anderson
16-Apr-2014From 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.
hama abdoul
08-Apr-2014Jason J
12-Feb-2014where are these three files :treeview.css, jquery-1.7.1.min.js and jquery.treeview.js
Thanks
Jason
Thekla Petro
22-Nov-2013Many 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
Chris Anderson
31-Oct-2013thanks.
Anh Lun
21-Aug-2013