Context menu in ASP.NET CORE Tree Grid Component

21 Dec 202218 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 property.

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.
@{
    var contextItems = new string[]{
        "SortAscending", "SortDescending","Edit", "Delete", "Save", "Cancel",
        "PdfExport", "ExcelExport", "CsvExport", "FirstPage", "PrevPage",
        "LastPage", "NextPage", "Indent", "Outdent" };
}

<ejs-treegrid id="TreeGrid" dataSource="@ViewBag.datasource" selectedRowIndex="2" contextMenuItems="contextItems" allowExcelExport="true" allowPdfExport="true" allowSorting="true" allowPaging="true" allowResizing="true" childMapping="Children" treeColumnIndex="1">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-editsettings allowAdding="true" allowEditing="true" allowDeleting="true" mode="Row"></e-treegrid-editsettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskId" headerText="Task ID" isPrimaryKey="true" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180" textAlign="Left"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" editType="datepickeredit" textAlign="Right" format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" editType="numericedit" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>
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> contextItems = new List<Object>();
    contextItems.Add(new { text = "Collapse the Row", target = ".e-content", id = "collapserow" });
    contextItems.Add(new { text = "Expand the Row", target = ".e-content", id = "expandrow" });
}

<ejs-treegrid id="TreeGrid" dataSource="@ViewBag.datasource" contextMenuOpen="onOpen" contextMenuClick="onClick"
              contextMenuItems="contextItems" allowExcelExport="true" allowPdfExport="true" allowSorting="true" allowPaging="true" childMapping="Children" treeColumnIndex="1">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskId" headerText="Task ID" isPrimaryKey="true" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180" textAlign="Left"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>

<script>
    function onOpen(args) {
        var treegrid = document.getElementById("TreeGrid").ej2_instances[0];
        var elem = args.event.target;
        var uid = elem.closest('.e-row').getAttribute('data-uid');
        if (ejs.base.isNullOrUndefined(ejs.base.getValue('hasChildRecords', treegrid.grid.getRowObjectFromUID(uid).data))) {
            args.cancel = true;
        } else {
            var flag = ejs.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 onClick(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.

@{
    ....
    var data = TreeGridItems.GetTreeData();
    List<object> contextItems = new List<Object>();
    contextItems.Add(new { text= "Edit Record", target= ".e-content", id= "Edit_record" });
    contextItems.Add(new { text = "Delete Record", target = ".e-content", id = "Delete_record" });
}

<ejs-treegrid id="TreeGrid" dataSource="@data" contextMenuOpen="ContextMenuOpen" contextMenuClick="ContextMenuClick" contextMenuItems="contextItems" allowPaging="true" childMapping="Children" treeColumnIndex="1">
    <e-treegrid-pagesettings pageSize="7"></e-treegrid-pagesettings>
    <e-treegrid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"  mode="Row"></e-treegrid-editSettings>
    <e-treegrid-columns>
        <e-treegrid-column field="TaskId" headerText="Task ID" isPrimaryKey="true" textAlign="Right" width="90"></e-treegrid-column>
        <e-treegrid-column field="TaskName" headerText="Task Name" width="180" textAlign="Left"></e-treegrid-column>
        <e-treegrid-column field="StartDate" headerText=" Start Date" textAlign="Right" format="yMd" type="date" width="90"></e-treegrid-column>
        <e-treegrid-column field="Duration" headerText="Duration" textAlign="Right" width="80"></e-treegrid-column>
    </e-treegrid-columns>
</ejs-treegrid>

<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 edit
        }
    }
    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 our ASP.NET Core Tree Grid feature tour page for its groundbreaking feature representations. You can also explore our ASP.NET Core Tree Grid example ASP.NET Core Tree Grid example to knows how to present and manipulate data.