Context menu in ASP.NET MVC Tree Grid Component
21 Dec 202217 minutes to read
The TreeGrid has options to show the context menu when right clicked on it. To enable this feature, you need to define either default or custom item in the ContextMenuItems
.
The default items are in the following table.
Items | Description |
---|---|
AutoFit |
Auto fit the current column. |
AutoFitAll |
Auto fit all columns. |
Edit |
Edit the current record. |
Delete |
Delete the current record. |
Save |
Save the edited record. |
Cancel |
Cancel the edited state. |
PdfExport |
Export the treegrid data as Pdf document. |
ExcelExport |
Export the treegrid data as Excel document. |
CsvExport |
Export the treegrid data as CSV document. |
SortAscending |
Sort the current column in ascending order. |
SortDescending |
Sort the current column in descending order. |
FirstPage |
Go to the first page. |
PrevPage |
Go to the previous page. |
LastPage |
Go to the last page. |
NextPage |
Go to the next page. |
AddRow |
Add new row to the treegrid. |
@(Html.EJS().TreeGrid("TreeGrid").AllowPaging().AllowSorting().AllowExcelExport()
.AllowPdfExport()
.AllowResizing()
.EditSettings(edit => edit.AllowAdding(true).AllowDeleting(true).AllowEditing(true).Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row))
.PageSettings(page => page.PageSize(7))
.DataSource((IEnumerable<object>)ViewBag.datasource)
.ContextMenuItems(
new List<object>() { "SortAscending",
"SortDescending", "Edit", "Delete",
"Save", "Cancel", "PdfExport", "ExcelExport", "CsvExport",
"FirstPage", "PrevPage", "LastPage", "NextPage", "Indent", "Outdent"
})
.Columns(col =>
{
col.Field("TaskId").HeaderText("Task ID").Width(90).IsPrimaryKey(true).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
col.Field("StartDate").HeaderText("Start Date").Format("yMd").Type("date").EditType("datepickeredit")
.TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("Duration").HeaderText("Duration").Width(80).EditType("numericedit")
.TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).ChildMapping("Children").SelectedRowIndex(2).TreeColumnIndex(1).Render())
public IActionResult Index()
{
var tree = TreeData.GetDefaultData();
ViewBag.datasource = tree;
return View();
}
Custom context menu items
The custom context menu items can be added by defining the ContextMenuItems
as a collection of ContextMenuItemModel.
Actions for this customized items can be defined in the ContextMenuClick
event.
In the below sample, we have shown context menu item for parent rows to expand or collapse child rows.
@{
List<object> ContextMenuitems = new List<object>();
ContextMenuitems.Add(new { text = "Collapse the Row", target = ".e-content", id = "collapserow" });
ContextMenuitems.Add(new { text = "Expand the Row", target = ".e-content", id = "expandrow" });
}
@(Html.EJS().TreeGrid("TreeGrid")
.DataSource((IEnumerable<object>)ViewBag.datasource)
.Columns(col =>
{
col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
col.Field("StartDate").HeaderText("Start Date").Format("yMd").Type("date").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).ChildMapping("Children").ContextMenuItems(ContextMenuitems).ContextMenuOpen("ContextMenuOpen").ContextMenuClick("ContextMenuClick")
.TreeColumnIndex(1).Render())
<script>
function ContextMenuOpen(args) {
var treegrid = document.getElementById("TreeGrid").ej2_instances[0];
var elem = args.event.target;
var uid = elem.closest('.e-row').getAttribute('data-uid');
if (ej.base.isNullOrUndefined(ej.base.getValue('hasChildRecords', treegrid.grid.getRowObjectFromUID(uid).data))) {
args.cancel = true;
} else {
var flag = ej.base.getValue('expanded', treegrid.grid.getRowObjectFromUID(uid).data);
var val = flag ? 'none' : 'block';
document.querySelectorAll('li#expandrow')[0].setAttribute('style', 'display: ' + val + ';');
val = !flag ? 'none' : 'block';
document.querySelectorAll('li#collapserow')[0].setAttribute('style', 'display: ' + val + ';');
}
}
function ContextMenuClick(args) {
var treegrid = document.getElementById("TreeGrid").ej2_instances[0];
treegrid.getColumnByField('TaskID');
if (args.item.id === 'collapserow') {
treegrid.collapseRow((treegrid.getSelectedRows()[0]), treegrid.getSelectedRecords()[0]);
} else {
treegrid.expandRow((treegrid.getSelectedRows()[0]), treegrid.getSelectedRecords()[0]);
}
}
</script>
public IActionResult Index()
{
var tree = TreeData.GetDefaultData();
ViewBag.datasource = tree;
return View();
}
Enable and disable context menu items dynamically
You can enable and disable the context menu items using the enableItems
method in contextMenuOpen
event.
@model List<TreeGridSample.Controllers.TreeGridItems>
@{
List<object> ContextMenuitems = new List<object>();
ContextMenuitems.Add(new { text= "Edit Record", target= ".e-content", id= "Edit_record" });
ContextMenuitems.Add(new { text= "Delete Record", target= ".e-content", id= "Delete_record" });
}
@(Html.EJS().TreeGrid("TreeGrid")
.DataSource((IEnumerable<object>)Model)
.Columns(col =>
{
col.Field("TaskId").HeaderText("Task ID").Width(90).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
col.Field("TaskName").HeaderText("Task Name").Width(180).Add();
col.Field("StartDate").HeaderText("Start Date").Format("yMd").Type("date").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width(90).Add();
col.Field("Duration").HeaderText("Duration").Width(80).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();
}).ChildMapping("Children")
.EditSettings(edit => edit.AllowAdding(true).AllowDeleting(true).AllowEditing(true).Mode(Syncfusion.EJ2.TreeGrid.EditMode.Row))
.ContextMenuItems(ContextMenuitems)
.ContextMenuOpen("ContextMenuOpen")
.ContextMenuClick("ContextMenuClick")
.TreeColumnIndex(1).Render())
<script>
function ContextMenuOpen(args) {
if (args.rowInfo.rowData.hasChildRecords == true) {
this.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'], true);//Enable edit
this.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'], false);//Disable delete
} else {
this.grid.contextMenuModule.contextMenu.enableItems(['Edit Record'], false);//Disable edit
this.grid.contextMenuModule.contextMenu.enableItems(['Delete Record'], true);//Enable delete
}
}
function ContextMenuClick(args) {
if(args.element.innerHTML == "Edit Record") {
this.startEdit(args.rowInfo.row);
}
else if (args.element.innerHTML == "Delete Record") {
this.deleteRecord(args.rowInfo.row);
}
}
</script>
public class HomeController : Controller
{
public ActionResult Index()
{
return View(TreeGridItems.GetTreeData());
}
}
public class TreeGridItems
{
public TreeGridItems() { }
public int TaskId { get; set; }
public string TaskName { get; set; }
public DateTime StartDate { get; set; }
public int Duration { get; set; }
public List<TreeGridItems> Children { get; set; }
public static List<TreeGridItems> GetTreeData()
{
List<TreeGridItems> BusinessObjectCollection = new List<TreeGridItems>();
TreeGridItems Record1 = null;
Record1 = new TreeGridItems()
{
TaskId = 1,
TaskName = "Planning",
StartDate = new DateTime(2016, 06, 07),
Duration = 5,
Children = new List<TreeGridItems>(),
};
TreeGridItems Child1 = new TreeGridItems()
{
TaskId = 2,
TaskName = "Plan timeline",
StartDate = new DateTime(2016, 06, 07),
Duration = 5
};
TreeGridItems Child2 = new TreeGridItems()
{
TaskId = 3,
TaskName = "Plan budget",
StartDate = new DateTime(2016, 06, 07),
Duration = 5
};
TreeGridItems Child3 = new TreeGridItems()
{
TaskId = 4,
TaskName = "Allocate resources",
StartDate = new DateTime(2016, 06, 07),
Duration = 5
};
Record1.Children.Add(Child1);
Record1.Children.Add(Child2);
Record1.Children.Add(Child3);
TreeGridItems Record2 = new TreeGridItems()
{
TaskId = 6,
TaskName = "Design",
StartDate = new DateTime(2021, 08, 25),
Duration = 3,
Children = new List<TreeGridItems>()
};
TreeGridItems Child5 = new TreeGridItems()
{
TaskId = 7,
TaskName = "Software Specification",
StartDate = new DateTime(2021, 08, 25),
Duration = 3
};
TreeGridItems Child6 = new TreeGridItems()
{
TaskId = 8,
TaskName = "Develop prototype",
StartDate = new DateTime(2021, 08, 25),
Duration = 3
};
TreeGridItems Child7 = new TreeGridItems()
{
TaskId = 9,
TaskName = "Get approval from customer",
StartDate = new DateTime(2024, 06, 27),
Duration = 2
};
Record2.Children.Add(Child5);
Record2.Children.Add(Child6);
Record2.Children.Add(Child7);
BusinessObjectCollection.Add(Record1);
BusinessObjectCollection.Add(Record2);
return BusinessObjectCollection;
}
}
NOTE
You can hide or show an item in context menu for specific area inside of treegrid by defining the
Target
property.
You can refer to ourASP.NET MVC Tree Grid
feature tour page for its groundbreaking feature representations. You can also explore ourASP.NET MVC Tree Grid example
to knows how to present and manipulate data.