How to apply HtmlAttributes for nodes in Treeview?
Description
You can easily map and apply the Html Attribute to TreeView items by using HtmlAttributes property in TreeViewModel class.
Solution
For applying the Html Attribute to the TreeView items, you have to configure some of the following properties in TreeView model.
- Map the HtmlAttributes property to the DataSource field.
Note: When LoadOnDemand is required, enable “LoadOnDemand” and assign “RequestMapper” value.
The value of HtmlAttributes should be in the following format,
- In order to assign the value to the attribute, use “=” character.
Example: “style=background-color: red; font-weight: bold; height: 21px; “
- To apply a multiple attribute value’s, use comma (“,”) to separate each attribute and its value.
Example: “style=background-color: red; font-weight: bold;, height= 21px, width=100px”
Sample Table Data:
Figure 1: Sample Table Data
Refer to the following code example for SQL Data Binding.
CSHTML
@Html.Syncfusion().TreeView("TreeView", "Databind",(TreeViewModel)ViewData["TreeView"])
C#
public ActionResult Index() { TreeViewModel model = new TreeViewModel(); var data = new DataClasses2DataContext().TreeViewTables; ViewData["DataSource"] = data; model.DataSource =(System.Collections.IEnumerable) ViewData["DataSource"]; var treeFields = new TreeViewFields(); treeFields.Id = "Id"; treeFields.ParentId = "ParentId"; treeFields.HtmlAttributes = "HtmlAtr"; treeFields.Text = "Text"; model.BindTo = treeFields; model.AllowEdit = false; ViewData["TreeView"] = model; return View(); }
Refer to the following code example for TreeView SQL Data binding with LoadOnDemand.
C#
public ActionResult Index() { TreeViewModel model = new TreeViewModel(); var data = new DataClasses2DataContext().TreeViewTables; ViewData["DataSource"] = data; model.DataSource =(System.Collections.IEnumerable) ViewData["DataSource"]; var treeFields = new TreeViewFields(); treeFields.Id = "Id"; treeFields.ParentId = "ParentId"; treeFields.HtmlAttributes = "HtmlAtr"; treeFields.Text = "Text"; model.BindTo = treeFields; model.AllowEdit = false; model.LoadOnDemand = true; model.RequestMapper = "LoadOnDemand"; ViewData["TreeView"] = model; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult LoadOnDemand(TreeViewModel treeViewModel, TreeViewItem b) { var subNodes= new DataClasses2DataContext().TreeViewTables.Where(c => c.ParentId == Convert.ToInt32(b.Value)); return new JsonResult { Data = subNodes }; }