This section briefly explains about how to include a simple TreeView in your ASP.NET MVC application. You can refer ASP.NET MVC Getting Started documentation page for introduction part part of the system requirements and configure the common specifications.
TreeView control can be rendered by using the EJS().TreeView()
tag helper in ASP.NET MVC application. Add the below simple code to your index.cshtml
page which is available within the Views/Home
folder, to initialize the TreeView.
The following example shows a basic TreeView control.
@Html.EJS().TreeView("listdata").Render();
public IActionResult Default()
{
return view();
}
TreeView can load data either from local data sources or remote data services. This can be done using the dataSource property that is a member of the fields property. The dataSource property supports array of JavaScript objects and DataManager. Here, an array of JSON values is passed to the TreeView control.
@Html.EJS().TreeView("listdata").Fields(field=>
field.Id("id").ParentID("pid").Selected("selected").
Expanded("expanded").Text("name").HasChildren("hasChild")
.DataSource(ViewBag.dataSource)).Render()
public IActionResult LocalData()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
id = 1,
name = "Australia",
hasChild = true,
expanded = true
});
listdata.Add(new
{
id = 2,
pid = 1,
name = "New South Wales",
});
listdata.Add(new
{
id = 3,
pid = 1,
name = "Victoria"
});
listdata.Add(new
{
id = 4,
pid = 1,
name = "South Australia"
});
listdata.Add(new
{
id = 6,
pid = 1,
name = "Western Australia",
});
listdata.Add(new
{
id = 7,
name = "Brazil",
hasChild = true
});
listdata.Add(new
{
id = 8,
pid = 7,
name = "Paraná"
});
listdata.Add(new
{
id = 9,
pid = 7,
name = "Ceará"
});
listdata.Add(new
{
id = 10,
pid = 7,
name = "Acre"
});
listdata.Add(new
{
id = 11,
name = "China",
hasChild = true
});
listdata.Add(new
{
id = 12,
pid = 11,
name = "Guangzhou"
});
listdata.Add(new
{
id = 13,
pid = 11,
name = "Shanghai"
});
listdata.Add(new
{
id = 14,
pid = 11,
name = "Beijing"
});
listdata.Add(new
{
id = 15,
pid = 11,
name = "Shantou"
});
listdata.Add(new
{
id = 16,
name = "France",
hasChild = true
});
listdata.Add(new
{
id = 17,
pid = 16,
name = "Pays de la Loire"
});
listdata.Add(new
{
id = 18,
pid = 16,
name = "Aquitaine"
});
listdata.Add(new
{
id = 19,
pid = 16,
name = "Brittany"
});
listdata.Add(new
{
id = 20,
pid = 16,
name = "Lorraine"
});
listdata.Add(new
{
id = 21,
name = "India",
hasChild = true
});
listdata.Add(new
{
id = 22,
pid = 21,
name = "Assam"
});
listdata.Add(new
{
id = 23,
pid = 21,
name = "Bihar"
});
listdata.Add(new
{
id = 24,
pid = 21,
name = "Tamil Nadu"
});
ViewBag.dataSource = listdata;
return View();
}
Output be like the below.